Python|将嵌套列表拆分为两个列表
给定一个嵌套的二维列表,任务是将嵌套列表拆分为两个列表,使得第一个列表包含每个子列表的第一个元素,第二个列表包含每个子列表的第二个元素。
方法#1:使用map, zip()
# Python code to demonstrate
# splitting nested list
# into 2 lists
# initialising nested lists
ini_list = [[1, 2], [4, 3], [45, 65], [223, 2]]
# printing initial lists
print ("initial list", str(ini_list))
# code to split it into 2 lists
res1, res2 = map(list, zip(*ini_list))
# printing result
print("final lists", res1, "\n", res2)
输出:
initial list [[1, 2], [4, 3], [45, 65], [223, 2]]
final lists [1, 4, 45, 223]
[2, 3, 65, 2]
方法 #2:使用列表推导
# python code to demonstrate
# splitting nested list
# into 2 lists
# initialising nested lists
ini_list = [[1, 2], [4, 3], [45, 65], [223, 2]]
# printing initial lists
print ("initial list", str(ini_list))
# code to split it into 2 lists
res1 = [i[1] for i in ini_list]
res2 = [i[0] for i in ini_list]
# printing result
print("final lists", str(res1), "\n", str(res2))
输出:
initial list [[1, 2], [4, 3], [45, 65], [223, 2]]
final lists [2, 3, 65, 2]
[1, 4, 45, 223]
方法 #3:使用operator.itemgetter()
# python code to demonstrate
# splitting nested list
# into 2 lists
from operator import itemgetter
# initialising nested lists
ini_list = [[1, 2], [4, 3], [45, 65], [223, 2]]
# printing initial lists
print ("initial list", str(ini_list))
# code to split it into 2 lists
res1 = list(map(itemgetter(0), ini_list))
res2 = list(map(itemgetter(1), ini_list))
# printing result
print("final lists", str(res1), "\n", str(res2))
输出:
initial list [[1, 2], [4, 3], [45, 65], [223, 2]]
final lists [1, 4, 45, 223]
[2, 3, 65, 2]