简体   繁体   English

Python:将字典列表转换为列表列表

[英]Python: Convert list of dictionaries to list of lists

I want to convert a list of dictionaries to list of lists. 我想将字典列表转换为列表列表。

From this. 由此。

d = [{'B': 0.65, 'E': 0.55, 'C': 0.31},
     {'A': 0.87, 'D': 0.67, 'E': 0.41},
     {'B': 0.88, 'D': 0.72, 'E': 0.69},
     {'B': 0.84, 'E': 0.78, 'A': 0.64},
     {'A': 0.71, 'B': 0.62, 'D': 0.32}]

To

[['B', 0.65, 'E', 0.55, 'C', 0.31],
 ['A', 0.87, 'D', 0.67, 'E', 0.41],
 ['B', 0.88, 'D', 0.72, 'E', 0.69],
 ['B', 0.84, 'E', 0.78, 'A', 0.64],
 ['A', 0.71, 'B', 0.62, 'D', 0.32]]

I can acheive this output from 我可以从获得此输出

l=[]
for i in range(len(d)):
    temp=[]
    [temp.extend([k,v]) for k,v in d[i].items()]
    l.append(temp)

My question is : 我的问题是

  • Is there any better way to do this? 有什么更好的方法吗?
  • Can I do this with list comprehension? 我可以使用列表理解吗?

Since you are using python 3.6.7 and python dictionaries are insertion ordered in python 3.6+ , you can achieve the desired result using itertools.chain : 由于您使用的是python 3.6.7,并且python字典在python 3.6+中是按插入顺序排列的 ,因此您可以使用itertools.chain获得所需的结果:

from itertools import chain

print([list(chain.from_iterable(x.items())) for x in d])
#[['B', 0.65, 'E', 0.55, 'C', 0.31],
# ['A', 0.87, 'D', 0.67, 'E', 0.41],
# ['B', 0.88, 'D', 0.72, 'E', 0.69],
# ['B', 0.84, 'E', 0.78, 'A', 0.64],
# ['A', 0.71, 'B', 0.62, 'D', 0.32]]

You can use a list comprehension: 您可以使用列表理解:

result = [[i for b in c.items() for i in b] for c in d]

Output: 输出:

[['B', 0.65, 'E', 0.55, 'C', 0.31], 
 ['A', 0.87, 'D', 0.67, 'E', 0.41], 
 ['B', 0.88, 'D', 0.72, 'E', 0.69], 
 ['B', 0.84, 'E', 0.78, 'A', 0.64], 
 ['A', 0.71, 'B', 0.62, 'D', 0.32]]

using lambda this can be done as 使用lambda可以做到

d = [{'B': 0.65, 'E': 0.55, 'C': 0.31},
     {'A': 0.87, 'D': 0.67, 'E': 0.41},
     {'B': 0.88, 'D': 0.72, 'E': 0.69},
     {'B': 0.84, 'E': 0.78, 'A': 0.64},
     {'A': 0.71, 'B': 0.62, 'D': 0.32}]

d1=list(map(lambda x: [j for i in x.items() for j in i], d))
print(d1)
"""
output

[['B', 0.65, 'E', 0.55, 'C', 0.31],
 ['A', 0.87, 'D', 0.67, 'E', 0.41],
 ['B', 0.88, 'D', 0.72, 'E', 0.69],
 ['B', 0.84, 'E', 0.78, 'A', 0.64],
 ['A', 0.71, 'B', 0.62, 'D', 0.32]]

"""

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM