首页 > 解决方案 > 为什么列表在 Python 的函数中被修改?

问题描述

我有以下代码:

def recursive_sort(list_to_sort, key):
"""
sort a list by a specified key recursively
"""
if len(list_to_sort) == 1:
    return list_to_sort
for i in range(0,len(list_to_sort) - 1):
    if list_to_sort[i][key] > list_to_sort[i + 1][key]:
        list_to_sort[i], list_to_sort[i+1] = list_to_sort[i+1], list_to_sort[i]

return recursive_sort(list_to_sort[:-1], key) + [list_to_sort[-1]]

我在 main() 中使用以下命令运行它:

sensor_list = [('4213', 'STEM Center', 0), ('4201', 'Foundations Lab', 1), ('4204', 'CS Lab', 2), ('4218', 'Workshop Room', 3), ('4205', 'Tiled Room', 4), ('Out', 'Outside', 10)]


print("\nOriginal unsorted list\n", sensor_list)
print("\nList sorted by room number\n", recursive_sort(sensor_list, 0))
print("\nList sorted by room name\n", recursive_sort(sensor_list, 1))
print("\nOriginal unsorted list\n", sensor_list)

这将打印输出:

Original unsorted list
 [('4213', 'STEM Center', 0), ('4201', 'Foundations Lab', 1), ('4204', 'CS Lab', 2), 
('4218', 'Workshop Room', 3), ('4205', 'Tiled Room', 4), ('Out', 'Outside', 10)]

List sorted by room number
 [('4201', 'Foundations Lab', 1), ('4204', 'CS Lab', 2), ('4205', 'Tiled Room', 4), 
('4213', 'STEM Center', 0), ('4218', 'Workshop Room', 3), ('Out', 'Outside', 10)]

List sorted by room name
 [('4204', 'CS Lab', 2), ('4201', 'Foundations Lab', 1), ('Out', 'Outside', 10), 
('4213', 'STEM Center', 0), ('4205', 'Tiled Room', 4), ('4218', 'Workshop Room', 3)]

Original unsorted list
 [('4204', 'CS Lab', 2), ('4201', 'Foundations Lab', 1), ('4213', 'STEM Center', 0), 
('4205', 'Tiled Room', 4), ('Out', 'Outside', 10), ('4218', 'Workshop Room', 3)]

为什么第一个和第四个打印返回不同的列表,sensor_list 不应该保持不变?

标签: pythonlistfunction

解决方案


正如@PresidentJamesK.Polk 提到的,这称为就地修改。这意味着无论您对参数/变量做什么,它都会在函数之外对其进行修改。发生这种情况是因为您正在修改参数本身而不是将其复制到列表中。为了防止这种情况,在你的功能中你可以说:

def recursive_sort(list_to_sort, key):
   result = list_to_sort.copy() # Or just regular assignment, but this is guaranteed to prevent in-place modification
   
   # Subsequent code with 'list_to_sort' replaced with result so
   # that it modifies the new, copied variable instead of the original

推荐阅读