简体   繁体   English

如何在 Python 中按另一个列表的顺序替换列表项

[英]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.一个简单的修复,替换后删除列表[0]。

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 .第二个注意事项,不要将您的列表命名为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您可以使用 counter to 每次将list2中的单词替换为list中的不同单词

I would also suggest not using the name list for your list since it has spacial meaning in python我还建议不要在您的列表中使用名称list ,因为它在 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: output:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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