首页 > 解决方案 > 使用 for 循环遍历元组列表和内部元组

问题描述

只是想知道如何遍历元组列表并同时遍历元组中的项目。

# I am able iterate over a list of tuples like this,
fruit_list = [('banana','apple','mango'),('strawberry', 'blueberry','raspberry')]
for fruit_tup in fruit_list:
    print(fruit_tup)

#output:
#('banana', 'apple', 'mango')
#('strawberry', 'blueberry', 'raspberry')

# Iterate through the items inside the tuples as so,
for (item1,item2,item3) in fruit_list:
    print(item1,item2,item3)

#output:
#banana apple mango
#strawberry blueberry raspberry

# This is incorrect but I tried to iterate over the tuples and the items inside the tuples as so
for fruit_tup,(item1,item2,item3) in fruit_list:
    print(fruit_tup,item1,item2,item3)

#required output:
#('banana', 'apple', 'mango') banana apple mango
#('strawberry', 'blueberry', 'raspberry') strawberry blueberry raspberry

关于如何做到这一点的任何想法?

标签: pythonlistloopstuplesnested-loops

解决方案


你需要一个嵌套循环:

fruit_list = [('banana','apple','mango'),('strawberry', 'blueberry','raspberry')]
for fruit_tup in fruit_list:
    for fruit in fruit_tup:
        print(fruit, end=' ') # no newline but a single space
    print() # now do a newline

印刷:

banana apple mango
strawberry blueberry raspberry

推荐阅读