python - 为什么列表在 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 不应该保持不变?
解决方案
正如@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
推荐阅读
- r - 甘特图显示建筑物建造过程的时间表
- google-chrome - 使用 Puppeteer 挂钩功能
- angular - 我在做什么是成功地允许我的导航栏在单击汉堡图标时打开......但没有让它关闭?
- csv - Nifi Groovy 脚本修改给出 MissingMethodException 错误的 csv 行
- javascript - 在 Javascript 类中不使用 this 关键字引用的变量是否引用全局变量?
- tags - 如何通过标签触发gitlab管道
- python - 如何从 Kaggle 下载文件并在 python 中处理它
- laravel - Laravel elastic.co 集成不起作用
- dart - 不能无条件调用方法“+”,因为接收者可以为“null”
- reactjs - ES5 中的 Material-ui 组件