【问题标题】:if list of objects contains value then return that object如果对象列表包含值,则返回该对象
【发布时间】:2020-11-13 17:36:12
【问题描述】:

我有一个对象列表。我想返回包含特定值的对象。

这是我的清单:

my_list = [
    {
        'machine': 'abc',
        'shapes':[
            {
                'shape': 'square',
                'width': 40,
                'height': 40
            },
            {
                'shape': 'rectangle',
                'width': 30,
                'height': 40
            }
        ]
    },
    {
        'machine': 'xyz',
        'shapes':[
            {
                'shape': 'square',
                'width': 40,
                'height': 40
            },
            {
                'shape': 'rectangle',
                'width': 30,
                'height': 40
            }
        ]
    },
    {
        'machine': 'xyz',
        'shapes':[
            {
                'shape': '/square/',
                'width': 40,
                'height': 40
            },
            {
                'shape': 'rectangle',
                'width': 30,
                'height': 40
            }
        ]
    }
]

我想要包含'shape': '/square/' 的整个列表。

我做到了:

for lst in my_list:
    # pprint(lst)
    if('xyz' in lst['machine']):
        pprint(lst['machine'])
        lst['shapes'] = [val for val in lst['shapes'] if val['shape'].startswith('/sq')]
        pprint(lst['shapes'])

这只会返回[{'height': 40, 'shape': '/square/', 'width': 40}]

有没有办法让我获得该列表中的所有内容(预期结果)

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

【问题讨论】:

    标签: python arrays list dictionary object


    【解决方案1】:
    my_value = "/square/"
    
    elements = []
    for element in my_list:
        for d in element['shapes']:
            if d['shape'] == my_value:
                elements.append(element)
                continue
    
    print(elements)
    

    【讨论】:

      【解决方案2】:

      方法如下:

      my_list = [{'machine': 'abc',
                  'shapes':[{'shape': 'square',
                             'width': 40,
                             'height': 40},
                            {'shape': 'rectangle',
                             'width': 30,
                             'height': 40}]},
                 {'machine': 'xyz',
                  'shapes':[{'shape': 'square',
                             'width': 40,
                             'height': 40},
                            {'shape': 'rectangle',
                             'width': 30,
                             'height': 40}]},
                 {'machine': 'xyz',
                  'shapes':[{'shape': '/square/',
                             'width': 40,
                             'height': 40},
                            {'shape': 'rectangle',
                             'width': 30,
                             'height': 40}]}]
      
      for dct in my_list:
          if any('/square/' in d.values() for d in dct['shapes']):
              print(dct['shapes'])
      

      输出:

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

      【讨论】:

        【解决方案3】:

        如果我理解正确的话,你希望得到你列表中的每一本词典。

        from pprint import pprint
        
        # my_list
        
        for i in my_list:
            pprint(i['shapes'][1])
        

        【讨论】:

          【解决方案4】:

          一行:

          filter(lambda y: any([it.get('shape') == '/square/' for it in y]), map(lambda x: x['shapes'], my_list))
          

          【讨论】:

            【解决方案5】:

            您可以在此处使用next 和推导式,因为您似乎只在此列表中寻找其中一种形状。

            我使用operator.itemgetter 来减少额外的查找,因此没有嵌套循环。

            from operator import itemgetter
            get_shape, get_shapes = itemgetter('shape'), itemgetter('shapes')
            next(shapes for shapes in map(get_shapes, my_list) if '/square/' in map(get_shape, shapes))
            

            结果:

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

            【讨论】:

              【解决方案6】:

              对您的代码进行最少的修改。您可以保留过滤器以测试元素是否存在并打印整个内容...

              for lst in my_list:
                  # pprint(lst)
                  if('xyz' in lst['machine']):
                      pprint(lst['machine'])
                      if len([lst['shapes'] for val in lst['shapes'] if val['shape'].startswith('/sq')]):
                          pprint(lst['shapes'])
              

              【讨论】:

              • 这可以使用列表理解来完成吗?如果我这样做 lst['shapes']= [lst['shapes'] for val in lst['shapes'] if val['shape'].startswith('/sq')] 我首先得到一个空数组
              • @nb_nb_nb 好吧......如果我理解正确......你可以摆脱你的第一个指令并将它们包含在列表理解操作中,但这最终会让它变得非常混乱(至少我是这么认为的)......就像pprint([shape for lst in my_list if 'xyz' in lst['machine'] for val in lst['shapes'] if val['shape'].startswith('/sq') for shape in lst['shapes']])
              猜你喜欢
              • 2018-06-14
              • 2017-07-15
              • 2019-04-29
              • 1970-01-01
              • 2023-04-01
              • 2020-12-08
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多