以下是一个示例代码,用于按指定的键将列表中的字典展平:
def flatten_list_of_dicts(lst, key):
result = []
for item in lst:
if key in item:
result.extend(item[key])
return result
# 示例数据
data = [
{'key1': [1, 2, 3]},
{'key2': [4, 5, 6]},
{'key1': [7, 8, 9]}
]
# 按指定的键将列表中的字典展平
flatten_result = flatten_list_of_dicts(data, 'key1')
print(flatten_result) # 输出: [1, 2, 3, 7, 8, 9]
在这个示例中,flatten_list_of_dicts
函数接受一个列表和一个键作为参数。它遍历列表中的每个字典,如果字典中存在指定的键,则将该键对应的值展开,添加到结果列表中。最后返回结果列表。
在示例数据中,使用键'key1'
展平了列表中的字典,并将结果打印出来。输出为[1, 2, 3, 7, 8, 9]
。
上一篇:按指定大小搜索图像
下一篇:按指定的月份掩盖NumPy数组