python - 如果使用列表推导,为什么函数不会更新列表,但在使用 for 循环时会更新
问题描述
这是我的计算机科学课程中的一个问题,我无法弄清楚为什么列表没有在函数中更新。
在下面的代码中,function_not_working 是我在测试期间提出的,但没时间找到另一个解决方案,我的朋友代码 function_working 正常工作,但在函数中打印“字符串”时都返回正确的列表更新。
def function_not_working(strings):
strings = [string[::-1].lower() for string in strings]
def function_working(strings):
for n in range(0, len(strings)):
new_string = strings[n].lower()
new_string = new_string[::-1]
strings[n] = new_string
# EDIT: THIS PART BELOW IS PART OF THE TESTING AND CANNOT BE EDITED
strings = ["ABC", "aBc", "abc"]
function(strings)
print(strings)
对于 function_not_working 预期:['cba', 'cba', 'cba'] 实际:["ABC", "aBc", "abc"]
解决方案
在function_not_working中,您正在创建另一个列表,该列表不引用通过函数的列表。这就是它不更新字符串列表的原因。在function_working中,您指的是作为参数传递的同一个列表。
要使function_not_working工作,请找到以下代码:
def function_not_working(strings):
strings = [string[::-1].lower() for string in strings]
return strings
strings = ["ABC", "aBc", "abc"]
strings = function_not_working(strings)
print(strings)
推荐阅读
- java - 在 JpaRepository 上测试 deleteById 不起作用
- python - Tkinter 过滤列表框不会更新
- python - 转换设置为 DataFrame
- mongodb - 检查提供的数据数组中的每个元素至少存在一行
- qt - 在 QT 安装程序框架中更改 TargetDirectory
- postgresql - Postgres trigger inserts all rows
- xamarin - 如何使用 FluentLayout 设置视图高度
- batch-file - ffmpeg 与输出文件相同的输入(需要临时文件但如何?)
- html - 无法抑制 R Markdown 中的错误消息?
- redis - 集群 3x3 时无法写入 redis 副本