python - 如何替换列表中的值
问题描述
我在遍历列表并应用将列表中的某些值更改为新值的算法时遇到问题。这是我当前的代码。我一直在以多种方式收到错误,我试图替换这些值。
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)
解决方案
您可以通过执行以下操作替换列表中的给定元素:
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)
推荐阅读
- c++ - prim算法的快速实现
- algorithm - 如果找到了 NP 完全问题的多项式时间算法,这是否意味着所有 NP 问题的时间复杂度相同?
- google-cloud-platform - 如何获取 Google Cloud Platform (GCP) 上所有防火墙规则的历史记录
- python - TypeError:维度值必须是整数或无或具有 __index__ 方法,得到 TensorShape([None, 1])
- algorithm - 使用 DFS 计算距离
- c# - Task.Run 不在后台 c# 中运行任务
- mysql - 这些数据集与子查询结果的内部联接不同
- apache-spark - 运行不同 Spark 版本的 History Server
- java - CompareTo 不允许比较两个对象
- rendering - D3D11 CreateDeferredContext 错误,但从未创建延迟渲染上下文