2024-04-18 03:34:53 发布
网友
我有一个嵌套的表单列表:
[[[a, [a1, a2, a3]],[b, [b1, b2, b3]], [c, [c1, c2, c3]]]
我怎样才能把它转换成初始元素的独特组合形式:
[[[a, b],[a1, a2, a3, b1, b2, b3]],[[a,c],[a1, a2, a3, c1, c2, c3]], [[b,c],[b1, b2, b3, c1, c2, c3]]]
我知道有很多清单,但我需要那种形式。我不知道从哪里开始。你知道吗
可以将字典与^{}一起使用:
from itertools import combinations, chain L = [['a', ['a1', 'a2', 'a3']], ['b', ['b1', 'b2', 'b3']], ['c', ['c1', 'c2', 'c3']]] d = dict(L) res = {comb: list(chain.from_iterable(map(d.__getitem__, comb))) \ for comb in combinations(d, 2)}
结果:
{('a', 'b'): ['a1', 'a2', 'a3', 'b1', 'b2', 'b3'], ('a', 'c'): ['a1', 'a2', 'a3', 'c1', 'c2', 'c3'], ('b', 'c'): ['b1', 'b2', 'b3', 'c1', 'c2', 'c3']}
或者,如果您喜欢嵌套列表:
res_lst = [[list(comb), list(chain.from_iterable(map(d.__getitem__, comb)))] \ for comb in combinations(d, 2)] # [[['a', 'b'], ['a1', 'a2', 'a3', 'b1', 'b2', 'b3']], # [['a', 'c'], ['a1', 'a2', 'a3', 'c1', 'c2', 'c3']], # [['b', 'c'], ['b1', 'b2', 'b3', 'c1', 'c2', 'c3']]]
在这两种情况下,都是为了减少Python级for循环的数量。你知道吗
for
您可以使用itertools.combinations:
itertools.combinations
from itertools import combinations l = [['a', ['a1', 'a2', 'a3']],['b', ['b1', 'b2', 'b3']], ['c', ['c1', 'c2', 'c3']]] print([[[i for i, _ in c], [i for _, l in c for i in l]] for c in combinations(l, 2)])
这将输出:
[[['a', 'b'], ['a1', 'a2', 'a3', 'b1', 'b2', 'b3']], [['a', 'c'], ['a1', 'a2', 'a3', 'c1', 'c2', 'c3']], [['b', 'c'], ['b1', 'b2', 'b3', 'c1', 'c2', 'c3']]]
没关系,我解决了。这是一个有效的例子。你知道吗
test = [['a', ['a1', 'a2', 'a3']],['b', ['b1', 'b2', 'b3']], ['c', ['c1', 'c2', 'c3']]] nested_list = [] for (idx1, idx2) in itertools.combinations(range(len(test)), r=2): (elem1, elem2), (elem3, elem4) = test[idx1], test[idx2] nested_list += [[elem1, elem3], elem2+elem4] nested_list [['a', 'b'], ['a1', 'a2', 'a3', 'b1', 'b2', 'b3'], ['a', 'c'], ['a1', 'a2', 'a3', 'c1', 'c2', 'c3'], ['b', 'c'], ['b1', 'b2', 'b3', 'c1', 'c2', 'c3']]
可以将字典与^{} 一起使用:
结果:
或者,如果您喜欢嵌套列表:
在这两种情况下,都是为了减少Python级
for
循环的数量。你知道吗您可以使用
itertools.combinations
:这将输出:
[[['a', 'b'], ['a1', 'a2', 'a3', 'b1', 'b2', 'b3']], [['a', 'c'], ['a1', 'a2', 'a3', 'c1', 'c2', 'c3']], [['b', 'c'], ['b1', 'b2', 'b3', 'c1', 'c2', 'c3']]]
没关系,我解决了。这是一个有效的例子。你知道吗
相关问题 更多 >
编程相关推荐