【问题标题】:Python: Convert list of dictionaries to list of listsPython:将字典列表转换为列表列表
【发布时间】:2019-04-17 16:05:51
【问题描述】:

我想将字典列表转换为列表列表。

从此。

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}]

[['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]]

我可以从

获得这个输出
l=[]
for i in range(len(d)):
    temp=[]
    [temp.extend([k,v]) for k,v in d[i].items()]
    l.append(temp)

我的问题是

  • 有没有更好的方法来做到这一点?
  • 我可以通过列表理解来做到这一点吗?

【问题讨论】:

  • 什么版本的python?顺序重要吗?你也可以使用itertools.chain - [list(chain.from_iterable(x.items())) for x in d]
  • @pault 我的python版本是3.6.7,顺序很重要。

标签: python python-3.x list dictionary


【解决方案1】:

由于您使用的是 python 3.6.7 和 python dictionaries are insertion ordered in 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]]

【讨论】:

  • 感谢您的回复和注意。所以如果我使用chain来确保它按顺序排列?
  • 不,3.6以下的字典不保证保持顺序。您必须在旧版本中使用OrderedDictchain这里只是用来flatten the tuples返回的items
【解决方案2】:

您可以使用列表推导:

result = [[i for b in c.items() for i in b] for c 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]]

【讨论】:

  • 这似乎是 OP 的要求,请注意items() 的顺序不是确定性的,可能会根据数据和运行而改变。
【解决方案3】:

使用 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]]

"""

【讨论】:

    猜你喜欢
    • 2015-07-23
    • 2011-11-18
    • 2022-08-16
    • 2019-02-10
    • 2015-06-02
    • 2015-10-16
    • 1970-01-01
    • 2017-04-23
    • 2021-10-13
    相关资源
    最近更新 更多