Skip to main content
 首页 » 编程设计

python之如何检查python对象列表中是否存在值

2025年05月04日8haluo1

如果我有一个简单的列表对象:

shapes = [ 
  { 
    'shape': 'square', 
    'width': 40, 
    'height': 40 
  }, 
  { 
    'shape': 'rectangle', 
    'width': 30, 
    'height': 40 
 
  } 
] 

如何快速检查值为 square 的 shape 是否存在?我知道我可以使用 for 循环来检查每个对象,但是有没有更快的方法?

提前致谢!

请您参考如下方法:

您可以使用内置函数 any 在一行中完成此操作:

if any(obj['shape'] == 'square' for obj in shapes): 
    print('There is a square') 

不过,这等同于 for 循环方法。


如果您需要取而代之的是获取索引,那么仍然有一种单行代码可以在不牺牲效率的情况下做到这一点:

index = next((i for i, obj in enumerate(shapes) if obj['shape'] == 'square'), -1) 

但是,这已经足够复杂了,最好还是坚持使用普通的 for 循环。

index = -1 
for i, obj in enumerate(shapes): 
    if obj['shape'] == 'square': 
        index = i 
        break