简体   繁体   中英

How to replace list items in order of another list in Python

Let's take this list:

list2 = ['<@25032923629058>', 'dad', 'awd', '<@65432156029058>', '<@98450239029058>']

I would like to replace the elements that start with <@ in order of this list:

list = ['dd#1111', 'dd#2222', 'dd#333']

Expected result:

['dd#1111', 'dad', 'awd', 'dd#2222', 'dd#333']

The following script changes every item that starts with <@ with the same value, which i want to avoid:

for i in range(len(list2)):
    if list2[i].startswith("<@"):
        list2[i] = list[0]
print(list2)

A simple fix, delete list[0] after replacing it.

for i in range(len(list2)):
    if list2[i].startswith("<@"):
        list2[i] = list[0]
        del list[0]
print(list2)

On a second note, don't name your lists as list . This is a bad practice that will hurt you in the long run.

you could use counter to in order to replace your words in list2 with different words from list each time

I would also suggest not using the name list for your list since it has spacial meaning in python

This should do the trick:

list2 = ['<@25032923629058>', 'dad', 'awd', '<@65432156029058>', '<@98450239029058>']
list = ['dd#1111', 'dd#2222', 'dd#333']
count=0
for i in range(len(list2)):
    if list2[i].startswith("<@"):
        list2[i] = list[count]
        count+=1
print(list2)

output:

['dd#1111', 'dad', 'awd', 'dd#2222', 'dd#333']

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