简体   繁体   中英

How to iterate over two lists in a specific order

I have two lists:

list1 = ['A','C','E','G','A']
list2 = ['B','D','F','H','N']

I would like to create these new names and append them to an empty list

A_vs_B
C_vs_D
E_vs_F
G_vs_H
A_vs_N

The structure is, the 1st item in list1 with 1st item in list 2 and so on. I only want these names.

This is what I've done so far

newlist = []
for i in list1:
    for j in list 2:
        name = i + '_vs_' + j
        newlist.append(name)

The problem with this it creates every possible combination of names between list1 & list2. How do I limit my loop to only produce names I want?

use zip() , which takes two lists (or other iterables) and creates an iterable of tuples. In the for loop unpack the tuple to the variables i and j

newlist = []
for i, j in zip(list1, list2):
    name = i + '_vs_' + j
    newlist.append(name)

You could further improve your code using format-strings:

newlist = []
for i, j in zip(list1, list2):
    newlist.append(f'{i}_vs_{j}')

and using list-comprehensions:

newlist = [f'{i}_vs_{j}' for i, j in zip(list1, list2)]

You could try:

list1 = ['A','C','E','G','A']
list2 = ['B','D','F','H','N']

newlist = []

for i in range(0, len(list1)):
    name = list1[i] + '_vs_' + list2[i]
    newlist.append(name)
print(newlist)

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