python - 如果对象列表包含值,则返回该对象
问题描述
我有一个对象列表。我想返回包含特定值的对象。
这是我的清单:
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}
]
解决方案
方法如下:
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}]
推荐阅读
- intellij-idea - IntelliJ IDEA 系列 IDE 中终端命令输入的自动化?
- reactjs - 如何添加自定义样式以响应 react-pagination-table 标题
- python - 我的 python 代码没有将 JSON 数据正确导入 CSV
- javascript - 淘汰赛表:突出显示表行
- vb.net - 如何初始化包含结构和简单元素混合的结构对象?
- angularjs - AngularJs ngNotify 点击关闭
- android - Android - 根据活动主机方向添加不同的片段
- security - TPM 与 CPU 有什么关系?
- css - 图片有时仅在 Chrome 移动版中尺寸错误
- javascript - 数组推送函数结果