如果我有一个简单的列表对象:
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
关于python - 如何检查python对象列表中是否存在值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46136665/