我有一个字典,在一个键-下包含多个列表下面是我的字典的输出示例:
print(dic)
输出:
{1: [[1, 2, 3, 4, 5, 6, 7],
[5, 1, 4, 34, 3, 65, 0, 2],
[2, 5, 4, 5, 7, 8, 4, 7]],
2: [[1, 5, 4, 5, 0, 1, 4, 6],
[2, 2, 3, 5, 6, 6, 3, 9]],
3: [[12, 35, 42, 53, 70, 71, 74, 76],
[6, 11, 16, 17, 38, 62, 66, 77]]}
我希望为每个键下的所有列表创建一个列表。因此,我正在寻找的输出示例看起来像这样:
{1: [[1, 2, 3, 4, 5, 6, 7, 5, 1, 4, 34, 3, 65, 0, 2, 2, 5, 4, 5, 7, 8, 4, 7]],
2: [[1, 5, 4, 5, 0, 1, 4, 6, 2, 2, 3, 5, 6, 6, 3, 9]],
3: [[12, 35, 42, 53, 70, 71, 74, 76, 6, 11, 16, 17, 38, 62, 66, 77]]}
我尝试了一个字典理解,几乎没有成功,以及一个for循环,我迭代了dic.items()。
可以使用字典推导式:
{key: [[item for sublist in value for item in sublist]] for key, value in data.items()}
这个输出:
{
1: [[1, 2, 3, 4, 5, 6, 7, 5, 1, 4, 34, 3, 65, 0, 2, 2, 5, 4, 5, 7, 8, 4, 7]],
2: [[1, 5, 4, 5, 0, 1, 4, 6, 2, 2, 3, 5, 6, 6, 3, 9]],
3: [[12, 35, 42, 53, 70, 71, 74, 76, 6, 11, 16, 17, 38, 62, 66, 77]]
}
Try withitertools.chain.from_iterable
:
>>> import itertools
>>> {k : [list(itertools.chain.from_iterable(v))] for k,v in dct.items()}
{1: [[1, 2, 3, 4, 5, 6, 7, 5, 1, 4, 34, 3, 65, 0, 2, 2, 5, 4, 5, 7, 8, 4, 7]],
2: [[1, 5, 4, 5, 0, 1, 4, 6, 2, 2, 3, 5, 6, 6, 3, 9]],
3: [[12, 35, 42, 53, 70, 71, 74, 76, 6, 11, 16, 17, 38, 62, 66, 77]]}
使用itertools.chain
:
from itertools import chain
out = {k: [list(chain.from_iterable(l))]
for k,l in dic.items()}
输出:
{1: [[1, 2, 3, 4, 5, 6, 7, 5, 1, 4, 34, 3, 65, 0, 2, 2, 5, 4, 5, 7, 8, 4, 7]],
2: [[1, 5, 4, 5, 0, 1, 4, 6, 2, 2, 3, 5, 6, 6, 3, 9]],
3: [[12, 35, 42, 53, 70, 71, 74, 76, 6, 11, 16, 17, 38, 62, 66, 77]]}