我在第一个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”,并且只显示如下的真实条件示例:如何为此循环编写
new_data_items = [{"ID":0x2222,  "Description":"data2",  "Writable":"TRUE"},
          {"ID":0x4444,   "Description":"data4", "Writable":"TRUE"}]

最佳答案

You could do something like the following:

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

关于python - Python从列表项中获取特定信息并创建新的列表项,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43345169/

10-11 18:14