【发布时间】: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