首页 > 解决方案 > 如果对象列表包含值,则返回该对象

问题描述

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

这是我的清单:

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}
]

标签: pythonarrayslistdictionaryobject

解决方案


方法如下:

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}]

推荐阅读