首页 > 解决方案 > 如何替换列表中的值

问题描述

我在遍历列表并应用将列表中的某些值更改为新值的算法时遇到问题。这是我当前的代码。我一直在以多种方式收到错误,我试图替换这些值。

array=[0,1,2,34,44,55,343,22,11,66,44,33]
for x in array:
    if x==0:
        y='Nan'
        array.replace(x,y)
    if x==1:
        y=0
        array.replace(x,y)
    if x==2:
        y=1
        array.replace(x,y)
    if x >= 3 and x < 23:
        y=(x-2)*50
        array.replace(x,y)
    if x >=23 and x <63:
        y=(x-12)*100
        array.replace(x,y)
    if x == 63:
        y=5500
        array.replace(x,y)
    if x >= 64 and x <= 67:
        y=(x-58)*1000
        array.replace(x,y)
    if x >= 68:
        y = 10000 
        array.replace(x,y)
print(array)

标签: python

解决方案


您可以通过执行以下操作替换列表中的给定元素:

list[index] = new_value

所以,

array[array.index(x)] = y # array.index(x) will give you the position of x in array

总之,我会这样做:

array=[0,1,2,34,44,55,343,22,11,66,44,33]

for i, x in enumerate(array): # use the direct i value instead of array.index(x)
    y = None
    if x == 0:
        y = 'NaN'
    elif x == 1:
        y = 0
    elif x == 2:
        y = 1
    elif x >= 3 and x < 23:
        y = (x-2)*50
    elif x >=23 and x <63:
        y = (x-12)*100
    elif x == 63:
        y = 5500
    elif x >= 64 and x <= 67:
        y = (x-58)*1000
    elif x >= 68:
        y = 10000 

    if y is not None:
        array[i] = y

print(array)

推荐阅读