[英]How to split a nested list into several lists in Python?
我的代码的输入格式如下:
第一行包含一个 integer n 。 接下来的n行包含一个空格分隔的整数列表。
我需要将每行的元素转换为一个列表,然后计算这些列表的笛卡尔积。 所以我已经到了将每行的元素转换为列表并将列表存储在“mylist”中的地步。
但是,由于“mylist”是一个嵌套列表,我确实知道如何计算每个元素的笛卡尔积。
from itertools import product
n = int(input())
mylist = []
for i in range(n):
elem = list(map(int, input().split()))
mylist.append(elem)
product = list(product(???))
例如,如果我的输入是:
2 # number of lists
1 2 3 # 1st list
4 5 6 # 2nd list
那么“mylist”将是:
my list = [[1, 2, 3], [4, 5, 6]]
我需要以下输出(“mylist”中两个列表的笛卡尔积):
[(1, 4), (1, 5), (1, 6), (2, 4), (2, 5), (2, 6), (3, 4), (3, 5), (3, 6)]
OBS:我不一定需要一个名为“mylist”的变量; 我只需要 2 条输入线的笛卡尔积。
提前致谢。
您可以只使用来自itertools
的product
,例如,
>>> l
[[1, 2, 3], [4, 5, 6]]
>>> import itertools
>>> list(itertools.product(*l))
[(1, 4), (1, 5), (1, 6), (2, 4), (2, 5), (2, 6), (3, 4), (3, 5), (3, 6)]
您所描述的正是笛卡尔积,在 python 中,它由库 itertools 实现。
使用itertools.product ,您可以用一行代码解决您的问题:
import itertools
my_list = [[1, 2, 3], [4, 5, 6]]
list(itertools.product(*my_list))
# output: [(1, 4), (1, 5), (1, 6), (2, 4), (2, 5), (2, 6), (3, 4), (3, 5), (3, 6)]
或者等价地,使用列表推导:
list1, list2 = my_list
[(x,y) for x in list1 for y in list2]
可能的product
实现如下:
def product(*my_list):
l_tuple = map(tuple, my_list)
result = [[]]
for t in l_tuple:
result = [a + [b] for a in result for b in t]
for prod in result:
yield tuple(prod)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.