如何在 Python 中更改列表中的项目?

问题描述

我有一个列表,我想在列表中找到值 20,如果它存在,用 3 替换第一个实例。

list1 = [5,10,15,20,25,50,20]

解决方法

执行线性搜索,或者如果序列可能会受到干扰,则对其进行排序并进行二分搜索。然后找到20,记下索引,直接替换。 例如

flag=0;
for(int i=0;i<list1.size();i++)
{
  if(list1[i]==20 && flag==0)
  {
     list1[i]=3;
    flag=1;
  }
}

对于蟒蛇: finding and replacing elements in a list

,

我是直接做的。 这对我有用:

while True:
    if 20 in list1:
        # getting index of the value
        val_index = list1.index(20)
        # replacing it by 3
        list1[val_index] = 3
        print(list1)
    else:
        break

如果您只想更改第一个值,则删除 while 循环:

if 20 in list1:
    # getting index of the value
    val_index = list1.index(20)
    # replacing it by 3
    list1[val_index] = 3
    print(list1)

我希望这有效:)