Python从列表项中获取特定信息并创建新的列表项

时间:2017-04-11 11:53:38

标签: python

我在第一个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"}]

4 个答案:

答案 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)

使用python列表压缩

[_ for _ in data_items if _.get('Writable') == 'TRUE']

点击此链接:https://repl.it/HEyl/0

答案 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