Python将字典中的项目合并 [英] Python combine items in a dictionary

查看:77
本文介绍了Python将字典中的项目合并的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设

我有一本字典A

A={'a':{0:[1,2,3],1:[4,5,6]},'b':{0:['u','v','w'],1:['x','y','z']}}

我想合并"a"和"b"中的所有元素

I want to combine all the elements in 'a' and 'b'

那个

[[1,2,3,'u','v','w'],
 [1,2,3,'x','y','z'],
 [4,5,6,'u','v','w'],
 [4,5,6,'x','y','z']]

我尝试过:

c=[]
for k,v in A.items():
    for i,t in v.items():
        c.append(t+t)

但是它没有得到想要的结果.

But it does not give the desired result.

推荐答案

作为Ajax1234上面概述的itertools方法的替代方法,您可以使用列表理解来做到这一点:

As an alternative to the itertools method outlined above by Ajax1234, you can do it with just list comprehensions:

首先将字典转换为列表列表:

Start with transforming your dict into a list of lists:

l_of_l = [list(i.values()) for i in A.values()]

然后将每个子列表与另一个列表迭代组合:

Then combine each sublist with another list iteration:

result = [i+v for i in l_of_l[0] for v in l_of_l[1]]

给你这个:

[[1, 2, 3, 'u', 'v', 'w'], [1, 2, 3, 'x', 'y', 'z'], [4, 5, 6, 'u', 'v', 'w'], [4, 5, 6, 'x', 'y', 'z']]

这篇关于Python将字典中的项目合并的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆