python 中的列表是不可变的吗?它们是否在函数中传递了值?

Are lists immutable in python? And are they passed value in a function?

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)

执行后我仍然得到相同列表的值

each_item 只是一个局部变量,它的值被 = 运算符覆盖。为其赋值不会影响原始列表。相反,您可以创建一个新列表并在返回之前填写它:

def threshold(the_list, thresholding_value, upper_val, lower_val):
    ret_list = list()
    for each_item in the_list:
        if each_item <= thresholding_value:
            ret_list.append(lower_val)
        else:
            ret_list.append(upper_val)
    return ret_list

您还可以通过使用列表理解显着缩短此代码:

def threshold(the_list, thresholding_value, upper_val, lower_val):
    return [lower_val if x <= thresholding_value else upper_val for x in the_list]

列表不是不可变的,但是当你循环一个列表时,循环控制变量会得到每一项的副本;它不是它的别名。因此更改它不会影响列表。

执行此操作的更 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]

列表绝对是可变的。会发生什么情况是您遍历列表,将每个元素依次复制到 each_item。 each_item 发生的事情与列表无关,因为它只是一个保存您的值的临时变量,而不是指针。

将 each_item 表示为 1 元素列表或 class 可以解决您的问题,但整个方法与 python 中通常的做法不同:为什么要创建一个当您可以为 return 值创建一个空列表并随时添加元素时,列表的副本?