gpt4 book ai didi

python - 如何在Python中将嵌套列表拆分为多个列表?

转载 作者:行者123 更新时间:2023-12-01 00:33:01 29 4
gpt4 key购买 nike

我的代码输入格式如下:

第一行包含一个整数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 条输入线的笛卡尔积。

提前致谢。

最佳答案

你所描述的正是Cartedian product ,在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]

可能的产品实现如下:

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)

关于python - 如何在Python中将嵌套列表拆分为多个列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58031203/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com