簡體   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