5 回答
TA贡献1744条经验 获得超4个赞
您的方法非常接近,但您需要先展平:
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]
TA贡献1906条经验 获得超10个赞
一种不同的,简单的方法:
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]
TA贡献1794条经验 获得超8个赞
您可以使用列表理解 (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]
TA贡献1780条经验 获得超1个赞
一种不同的,简单的方法:
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]
TA贡献1801条经验 获得超8个赞
这个怎么样?
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))
添加回答
举报