zak*_*ako 2 python dictionary list python-2.7
我有这样的列表的字典:
y = {'a':[1,2,3], 'b':[4,5], 'c':[6]}
Run Code Online (Sandbox Code Playgroud)
我想将dict转换为元组列表,其中每个元素都是一个包含dict的一个键和值列表中的一个元素的元组:
x = [
('a',1),('a',2),('a',3),
('b',4),('b',5),
('c',6)
]
Run Code Online (Sandbox Code Playgroud)
我的代码是这样的:
x = reduce(lambda p,q:p+q, map(lambda (u,v):[(u,t) for t in v], y.iteritems()))
Run Code Online (Sandbox Code Playgroud)
这样的代码似乎难以阅读,所以我想知道是否有任何pythonic方式,或者更确切地说,是否有一种列表理解方式来做这样的事情?
你可以这样做,
>>> y = {'a':[1,2,3], 'b':[4,5], 'c':[6]}
>>> [(i,x) for i in y for x in y[i]]
[('a', 1), ('a', 2), ('a', 3), ('c', 6), ('b', 4), ('b', 5)]
Run Code Online (Sandbox Code Playgroud)