def threshold(the_list,thresholding_value,upper_val,lower_value):
ret_list=list(the_list)
for each_item in ret_list:
if each_item <= thresholding_value:
each_item=lower_value
else:
each_item=upper_val
return ret_list
temp=[-1,2,5,3,-1,5,32,-6]
ttt=r.threshold(temp,0,1,0)
执行后我仍然得到相同列表的值
请您参考如下方法:
列表不是不可变的,但是当你循环一个列表时,循环控制变量会得到每一项的副本;它不是它的别名。因此更改它不会影响列表。
执行此操作的更 Pythonic 方式是列表推导式返回新列表:
def threshold(the_list, threshold, upper, lower):
return [lower if item <= threshold else upper for item in the_list]
threshold([-1,2,5,3,-1,5,32,-6],0,1,0)
# => [0, 1, 1, 1, 0, 1, 1, 0]
