Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

['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)

>Solution :

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']
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading