基本上,我有这个:
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所建议的,对于Python版本低于3.7的情况要小心:键是无序的,因此您可能最终得到未排序的值。
您可以轻松地完成它,像这样 -
my_list = [{'a': 1, 'b': 1}, {'c': 1}]
res = list(map(list,my_list))
print(res)
输出:
[['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']]
list(map(list, my_list))
- Yevhen Kuzmovych