简体   繁体   中英

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

Just wondering how to iterate over a list of tuples and also iterate through the items inside the tuples at the same time.

# 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

Any idea on how to do this?

You need a nested loop:

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

Prints:

banana apple mango
strawberry blueberry raspberry

You can do the bellow:

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

To create a list of your outputs:

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

If you directly want to print them:

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

If you want to loop through the tupels and the list at the same time:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM