代码之家  ›  专栏  ›  技术社区  ›  Trung Tran

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

  •  6
  • Trung Tran  · 技术社区  · 9 年前

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

    shape 有价值的 square 存在?我知道我可以用 for 循环检查每个对象,但有没有更快的方法?

    提前感谢!

    6 回复  |  直到 9 年前
        1
  •  20
  •   Eric Zhang    9 年前

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

    if any(obj['shape'] == 'square' for obj in shapes):
        print('There is a square')
    

    不过,这相当于for-loop方法。


    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
    
        2
  •  7
  •   cs95 abhishek58g    9 年前

    看,马,没有循环。

    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
    
        3
  •  2
  •   ettanany    9 年前

    使用 list comprehension 您可以执行以下操作:

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

    filter() :

    if list(filter(lambda item: item['shape'] == 'square', shapes)):
        # do something
    
        4
  •  1
  •   Ajax1234    9 年前

    get 要获得更稳健的解决方案:

    if any(i.get("shape", "none") == "square" for i in shapes):
        #do something
        pass
    
        5
  •  1
  •   stachel    9 年前

    仅在存在时检查:

    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']
    
        6
  •  1
  •   wwii    9 年前
    import operator
    shape = operator.itemgetter('shape')
    shapez = map(shape, shapes)
    print('square' in shapez)