【发布时间】:2017-10-29 18:11:35
【问题描述】:
我有一个列表。
在每个列表中都有几千个字典列表。一个列表可能包含多个字典、一个字典,或者它可能是空的。
这是一个精简列表,其中包含三个示例行:
list_of_lists = [[], [{'text': 'analytics', 'indices': [18, 28]}, {'text': 'datascience', 'indices': [35, 47]}, {'text': 'restaurants', 'indices': [54, 66]}, {'text': 'machinelearning', 'indices': [92, 108]}, {'text': 'bigData', 'indices': [109, 117]}, {'text': 'CRM', 'indices': [118, 122]}], [{'text': 'python', 'indices': [49, 56]}, {'text': 'datascience', 'indices': [57, 69]}]
所以在这个列表中有一个空列表,一个包含 6 个字典的列表,一个包含 2 个字典的列表。
我需要从包含“文本”:“SOME_STRING”的键:值对中提取值。
另外,重要的是,每个值都应该返回一个与原始输入列表具有相同索引的列表中。换句话说,例如,对于 6 个 key:value 对的第二个列表,所有 6 个值都应返回到与原始 list_of_lists 中相同索引处的列表中
所以这是我想要的上述示例的输出:
list_of_values = [[], ['analytics', 'datascience', 'restaurants', 'machinelearning', 'bigData', 'CRM', 'python'], ['python', 'datascience']]
我已经编写了下面的代码,几乎可以满足我的要求。它返回所有这些字符串的列表,但它不会在相同的索引处返回它们,它还返回我不想要的索引字典。
new_list_of_value_lists = []
for line in list_of_lists:
for dictionary in line:
for key, value in dictionary.items():
new_list_of_value_lists.append(value)
【问题讨论】:
标签: python json list dictionary