Home > Blockchain >  How to replace list items in order of another list in Python
How to replace list items in order of another list in Python

Time:07-31

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)

CodePudding user response:

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.

CodePudding user response:

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']
  • Related