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

标签 python list object dictionary

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

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

  }
]

如何快速检查值为 squareshape 是否存在?我知道我可以使用 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/

相关文章:

python - 在 Go 中枚举常量的最佳方法

Python读取sdf/mdl坐标: How to read until two spaces are met?

c++ - 什么对我来说更好 : vector or list?

返回对象时的 JavaScript 问题

javascript - CMS 的动态网络抓取表

python - 如果元素等于某个容差,我可以使用 numpy 快速设置 float 差异吗

python - 如何从geoalchemy2的查询结果中获取lng lat值

c# - 检查值是否是 C# 中一组值中的一个的最简单方法?

c# - 我怎么知道某些扩展方法是否使用 'mutate' 对象?

javascript - 字母数字对象属性名称