繁体   English   中英

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

[英]How to check if value exists in python list of objects

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

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

看,没有循环

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

使用filter()

if list(filter(lambda item: item['shape'] == 'square', shapes)):
    # do something

仅检查是否存在:

any(shape.get('shape') == 'square' for shape in shapes)

获取第一个索引(如果不存在StopIteration异常,则该异常)。

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM