使用 for 循环遍历元组列表和元组内部

Iterating over a list of tuples and inside tuples using a for loop

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

# 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

知道怎么做吗?

您可以执行以下操作:

for lst in fruit_list:
    for fruit in lst:
        print(fruit, end=' ')
    print()

您需要一个嵌套循环:

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

要创建输出列表:

lst = [('banana','apple','mango'),('strawberry', 'blueberry','raspberry')]
output = [" ".join(tupel) for tupel in lst]

如果你想直接打印它们:

[print(" ".join(tupel)) for tupel in lst]

如果你想同时遍历元组和列表:

output = [fruit for tupel in lst for fruit in tupel]