简体   繁体   English

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

[英]How to split a nested list into several lists in Python?

The input format of my code is as follows:我的代码的输入格式如下:

The first line contains an integer n .第一行包含一个 integer n The next n lines contain a list of space separated integers.接下来的n行包含一个空格分隔的整数列表。

What I need is to convert the elements of each line into a list and then compute the cartesian product of those lists.我需要将每行的元素转换为一个列表,然后计算这些列表的笛卡尔积。 So I've reached the point where I convert the elements of each line into a list and store the lists in "mylist".所以我已经到了将每行的元素转换为列表并将列表存储在“mylist”中的地步。

However, since "mylist" is a nested list, I do know how to compute the cartesian product of each element.但是,由于“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(???))

For example, if my input is:例如,如果我的输入是:

2 # number of lists
1 2 3 # 1st list
4 5 6 # 2nd list

then "mylist" is gonna be:那么“mylist”将是:

my list = [[1, 2, 3], [4, 5, 6]]

and I need the following outupt (cartesian product of the 2 lists in "mylist"):我需要以下输出(“mylist”中两个列表的笛卡尔积):

[(1, 4), (1, 5), (1, 6), (2, 4), (2, 5), (2, 6), (3, 4), (3, 5), (3, 6)]

OBS: I don't necessarily need a variable called "mylist"; OBS:我不一定需要一个名为“mylist”的变量; I just need the cartesian product of the 2 input lines.我只需要 2 条输入线的笛卡尔积。

Thanks in advance.提前致谢。

You can just use product from itertools like,您可以只使用来自itertoolsproduct ,例如,

>>> 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)]

What you described is exactly the Cartedian product , and in python it is implemented by the library itertools.您所描述的正是笛卡尔积,在 python 中,它由库 itertools 实现。
Using itertools.product , you can solve your problem with a single line of code:使用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)]

Or equivantelly, using list comprehension:或者等价地,使用列表推导:

list1, list2 = my_list
[(x,y) for x in list1 for y in list2]

A possible product implementation could be the following:可能的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.

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