Python - 遍历元组列表


列表是一个重要的容器,在日常编程和 Web 开发中几乎在每个代码中都会使用,使用得越多,掌握它的要求就越高,因此了解其操作非常有必要。

示例

# using itertools.ziplongest
# import library
from itertools import zip_longest  
# initialising listoflist
test_list = [
   [('11'), ('12'), ('13')],
   [('21'), ('22'), ('23')],
   [('31'), ('32'), ('33')]
   ]
# printing intial list
print ("Initial List = ", test_list)  
# iterate list tuples list of list into single list
res_list = [item for my_list in zip_longest(*test_list)
for item in my_list if item]
# print final List
print ("Resultant List = ", res_list)
# using itertools.ziplongest + lambda + chain
# import library
from itertools import zip_longest, chain  
# initialising listoflist
test_list = [
   [('11'), ('12'), ('13')],
   [('21'), ('22'), ('23')],
   [('31'), ('32'), ('33')]
   ]
# printing intial list
print ("Initial List = ", test_list)  
# iterate list tuples list of list into single list
# using lambda + chain + filter
res_list = list(filter(lambda x: x, chain(*zip_longest(*test_list))))
# print final List
print ("Resultant List = ", res_list)
# list using list comprehension
# initialising listoflist
test_list = [
   [('11'), ('12'), ('13')],
   [('21'), ('22'), ('23')],
   [('31'), ('32'), ('33')]
]
# printing intial list
print ("Initial List = ", test_list)
# iterate list tuples list of list into single list
# using list comprehension
res_list = [item for list2 in test_list for item in list2]
# print final List
print ("Resultant List = ", res_list)

更新于:2020-08-06

144 次浏览

开启你的 职业生涯

通过完成课程获得认证

开始
广告