简体   繁体   English

如何从存储在元组列表列表中的两个元素元组中创建两个列表

[英]How to make two lists out of two-elements tuples that are stored in a list of lists of tuples

I have a list which contains many lists and in those there 4 tuples.我有一个列表,其中包含许多列表,其中有 4 个元组。

my_list = [[(12, 1), (10, 3), (4, 0), (2, 0)],
           [(110, 1), (34, 2), (12, 1), (55, 3)]]

I want them in two separate lists like:我希望它们在两个单独的列表中,例如:

my_list2 = [12,10,4,2,110,34,12,55]
my_list3 = [1,3,0,0,1,2,1,3]

my attempt was using the map function for this.我的尝试是为此使用map function。

my_list2 , my_list3 = map(list, zip(*my_list))

but this is giving me an error:但这给了我一个错误:

ValueError: too many values to unpack (expected 2)

Your approach is quite close, but you need to flatten first:您的方法非常接近,但您需要先展平:

from itertools import chain

my_list = [[(12, 1), (10, 3), (4, 0), (2, 0)], [(110, 1), (34, 2), (12, 1), (55, 3)]]

my_list2 , my_list3 = map(list,zip(*chain.from_iterable(my_list)))

my_list2
# [12, 10, 4, 2, 110, 34, 12, 55]

my_list3
# [1, 3, 0, 0, 1, 2, 1, 3]

A different, plain approach:一种不同的,简单的方法:

my_list = [[(12, 1), (10, 3), (4, 0), (2, 0)], [(110, 1), (34, 2), (12, 1), (55, 3)]]

first = []
second = []

for inner in my_list:
    for each in inner:
        first.append(each[0])
        second.append(each[1])

print(first)  # [12, 10, 4, 2, 110, 34, 12, 55]
print(second)  # [1, 3, 0, 0, 1, 2, 1, 3]

You can use list comprehension (5.1.3) .您可以使用列表理解 (5.1.3)

First number of tuple:第一个元组数:

my_list2 = [tuple[0] for inner in my_list for tuple in inner]

Second number of tuple:第二个元组数:

my_list3 = [tuple[1] for inner in my_list for tuple in inner]

Try it:试试看:

my_list = [[(12, 1), (10, 3), (4, 0), (2, 0)], [(110, 1), (34, 2), (12, 1), (55, 3)]]

my_list2, my_list3 = map(list, zip(*[j for i in my_list for j in i]))
print(my_list2)
# [12, 10, 4, 2, 110, 34, 12, 55]
print(my_list3)
# [1, 3, 0, 0, 1, 2, 1, 3]

How about this?这个怎么样?

my_list = [[(12, 1), (10, 3), (4, 0), (2, 0)], [(110, 1), (34, 2), (12, 1), (55, 3)]]

flatten = lambda l: [item for my_list in l for item in my_list]

list1, list2 = zip(*flatten(my_list))

Here is one way:这是一种方法:

my_list = [[(12, 1), (10, 3), (4, 0), (2, 0)], [(110, 1), (34, 2), (12, 1), (55, 3)]]

my_list2 = [a for b in [[t[0] for t in my_list[i]] for i,n in enumerate(my_list)] for a in b]
my_list3 = [a for b in [[t[1] for t in my_list[i]] for i,n in enumerate(my_list)] for a in b]

print(my_list2)
print(my_list3)

Output: Output:

[12, 10, 4, 2, 110, 34, 12, 55]
[1, 3, 0, 0, 1, 2, 1, 3]

How about a minimalist solution:一个极简的解决方案怎么样:

my_list = [[(12, 1), (10, 3), (4, 0), (2, 0)], [(110, 1), (34, 2), (12, 1), (55, 3)]]

my_list2, my_list3 = zip(*sum(my_list, []))

print(my_list2)
print(my_list3)

OUTPUT OUTPUT

> python3 test.py
(12, 10, 4, 2, 110, 34, 12, 55)
(1, 3, 0, 0, 1, 2, 1, 3)
>

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

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