我在第一个python项目中使用list。
data_items = [{"ID":0x1111, "Description":"data1", "Writable":"FALSE"},
{"ID":0x2222, "Description":"data2", "Writable":"TRUE"},
{"ID":0x3333, "Description":"data3", "Writable":"FALSE"},
{"ID":0x4444, "Description":"data4", "Writable":"TRUE"}]
我想使用另一个列表名称“new_data_items”并仅显示TRUE条件,如下例所示:如何为此循环编写
new_data_items = [{"ID":0x2222, "Description":"data2", "Writable":"TRUE"},
{"ID":0x4444, "Description":"data4", "Writable":"TRUE"}]
答案 0 :(得分:4)
您可以使用filter执行此操作:
filter(lambda x: x['Writable'] == 'TRUE', data_items)
请注意,filter会返回一个迭代器,因此您可能还想将其转换为列表:
list(filter(lambda x: x['Writable'] == 'TRUE', data_items))
如果'可写'某些记录可能不存在字段,请使用.get
替换索引:
list(filter(lambda x: x.get('Writable') == 'TRUE', data_items))
答案 1 :(得分:2)
答案 2 :(得分:1)
您可以执行以下操作:
new_data_items = []
for item in data_items:
if item['Writable'] == 'TRUE':
new_data_items.append(item)
但是列表推导会更快,更简洁:
new_data_items = [item for item in data_items if item['Writable'] == 'TRUE']
答案 3 :(得分:1)
data_items = [{"ID":0x1111, "Description":"data1", "Writable":"FALSE"},
{"ID":0x2222, "Description":"data2", "Writable":"TRUE"},
{"ID":0x3333, "Description":"data3", "Writable":"FALSE"},
{"ID":0x4444, "Description":"data4", "Writable":"TRUE"}]
new_data = list()
for element in data_items:
value = element.get('Writable')
if not value == "FALSE":
new_data.append(element)
print new_data