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

如何检查python对象列表中是否存在值,python,list,object,dictionary,Python,List,Object,Dictionary,如果我有一个简单的对象列表: shapes = [ { 'shape': 'square', 'width': 40, 'height': 40 }, { 'shape': 'rectangle', 'width': 30, 'height': 40 } ] 如何快速检查是否存在值为方形的形状?我知道我可以使用for循环检查每个对象,但有没有更快的方法 提前谢谢 您可以使用内置函数any在一行中完成此操作: 如果有(obj['s

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

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

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


提前谢谢

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

如果有(obj['shape']=='square'表示形状中的obj):
打印('有一个正方形')
不过,这相当于for循环方法


如果您需要获取索引,那么仍然有一个单行程序可以在不牺牲效率的情况下实现这一点:

index=next((i代表i,如果obj['shape']=='square'),则枚举(形状)中的obj,-1)
然而,这已经够复杂了,所以最好还是坚持使用正常的for循环

index=-1
对于i,枚举中的obj(形状):
如果obj['shape']=='square':
指数=i
打破
看一看ma,没有循环

import json
import re

if re.search('"shape": "square"', json.dumps(shapes), re.M):
    ... # "square" does exist
如果要检索与
square
关联的索引,需要使用
for…else对其进行迭代:

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

print(i) 

性能

100000 loops, best of 3: 10.5 µs per loop   # regex
1000000 loops, best of 3: 341 ns per loop   # loop

您可以尝试使用
get
来获得更健壮的解决方案:

if any(i.get("shape", "none") == "square" for i in shapes):
    #do something
    pass
使用该工具,您可以执行以下操作:

if [item for item in shapes if item['shape'] == 'square']:
    # do something
使用:


仅在其存在时进行检查:

any(shape.get('shape') == 'square' for shape in shapes)
获取第一个索引(如果它不存在,您将获得StopIteration异常)

所有指标:

[i for i, shape in enumerate(shapes) if shape.get('shape') == 'square']

any(shape.get('shape')=='square'表示形状中的形状)
为什么你认为for循环很慢?太好了!按照这种方法,是否也有快速返回该形状索引的方法?这里的性能如何?能否提供与for循环的性能比较solution@SarathSadasivanPillai哦,绝对没有可比性。循环比正则表达式快得多。我想OP接受我的答案是因为我答案的第二部分,而不是第一部分。测试我的,测试我的-
地图中的“正方形”(operator.itemgetter('shape'),shapes)
不同的机器/cpu/速度-->苹果和橘子。谢谢。虽然简单,但此解决方案会对任何不可JSON序列化的对象抛出错误。即使对象是可序列化的,也可能被黑客攻击:
next(i for i, shape in enumerate(shapes) if shape.get('shape') == 'square')
[i for i, shape in enumerate(shapes) if shape.get('shape') == 'square']
import operator
shape = operator.itemgetter('shape')
shapez = map(shape, shapes)
print('square' in shapez)