繁体   English   中英

Python中嵌套列表中的列表组合

[英]Combinations by list in nested lists in Python

我有一个 [[a,b,c,d], [a,c,d], [b,d,e,f,g,h],....,[c,d, a,b]] 并且我必须将每个嵌套列表的元素(单独)组合成 2 元组以形成单个 2 元组列表。 我试图用下面的代码来做,但它只结合了第一个列表的元素:

def totwotuples(my_list):
    for i in range(len(my_list)):
        for j in range(len(my_list[i])):
           twotuples = itertools.combinations(my_list[i], 2)
    return[k for k in twotuples]

如何遍历所有嵌套列表?

您可以使用itertools.chainitertools.chain.from_iterable来组合子列表的结果。

import itertools

lst = [[1, 2], [3, 4]]

output = itertools.chain.from_iterable(itertools.product(sublst, repeat=2) for sublst in lst)
output = list(output) # convert to a list
print(output) # [(1, 1), (1, 2), (2, 1), (2, 2), (3, 3), (3, 4), (4, 3), (4, 4)]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM