python 如何用存储在元组列表的列表中的两个元素元组制作两个列表

mspsb9vt  于 2023-05-29  发布在  Python
关注(0)|答案(8)|浏览(201)

我有一个列表,其中包含许多列表,并在这些有4元组。

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

我希望它们在两个单独的列表中,如:

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

我的尝试是使用map函数。

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

但这给了我一个错误:

ValueError: too many values to unpack (expected 2)
lvjbypge

lvjbypge1#

你的方法是相当接近,但你需要先变平:

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

pxyaymoc2#

另一种简单的方法:

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

q3aa05253#

试试看:

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

izkcnapc4#

你可以使用列表解析(5.1.3)。
元组的第一个数量:

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

元组的第二个数量:

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

3ks5zfa05#

这个怎么样?

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

fkvaft9z6#

这里有一种方法:

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)

输出:

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

58wvjzkj7#

最低限度的解决方案如何:

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)

输出

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

gudnpqoy8#

将元组列表转换为2d数组,然后对数组进行切片

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

a = np.array(my_list)
my_list2= np.array([])
my_list3= np.array([])
my_list2=np.append(my_list2,[item[:,0] for item in a])
my_list3=np.append(my_list3,[item[:,1] for item in a])
print(my_list2)
print(my_list3)

输出:

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

相关问题