Python 从字典列表中提取列表
基本上我有:Python 从字典列表中提取列表,python,list,Python,List,基本上我有: my_list = [{'a': 1, 'b': 1}, {'c': 1}] 我想要这样的输出: new_list = [['a', 'b'],['c']] 我尝试了自己的代码,但它只返回以下内容: ['a', 'b', 'c'] 以下是一个可能的解决方案: result = [list(d) for d in my_list] 它基本上相当于: result = list(map(list, my_list)) 请注意,使用list(d.keys())相当于list(
my_list = [{'a': 1, 'b': 1}, {'c': 1}]
我想要这样的输出:
new_list = [['a', 'b'],['c']]
我尝试了自己的代码,但它只返回以下内容:
['a', 'b', 'c']
以下是一个可能的解决方案:
result = [list(d) for d in my_list]
它基本上相当于:
result = list(map(list, my_list))
请注意,使用list(d.keys())
相当于list(d)
正如meowgoesthedog在一篇评论中所建议的那样,使用早于3.7的Python版本时要小心:键没有排序,因此您可能最终会得到未排序的值。您可以像-
my_list = [{'a': 1, 'b': 1}, {'c': 1}]
res = list(map(list,my_list))
print(res)
输出:
[['a', 'b'], ['c']]
[['a', 'b'], ['c']]
如果你不太明白上面的工作原理,这里有一个更简单的版本-
my_list = [{'a': 1, 'b': 1}, {'c': 1}]
res = []
for dicts in my_list:
res.append(list(dicts))
# The above process is equivalent to the shorthand :
# res = [ list(dicts) for dicts in my_list ]
print(res)
输出:
[['a', 'b'], ['c']]
[['a', 'b'], ['c']]
请发布您自己的代码,并指定您的Python版本(在3.7字典无序之前)。
list(map(list,my_list))