python - 为什么如果使用列表理解该函数不会更新列表,但在使用 for 循环时会更新列表

标签 python

这是我的计算机科学类(class)中的一个问题,我不明白为什么该列表没有在函数内更新。

在下面的代码中,function_not_working是我在测试期间想出的,但没时间找到另一个解决方案,我 friend 的代码,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)

对于功能不工作 预期:['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)

关于python - 为什么如果使用列表理解该函数不会更新列表,但在使用 for 循环时会更新列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57903460/

相关文章:

python - 如何使用 tkinter 更新框架?

python - 在 python 中使用 dbf 库读取更改

python - 在 python mechanize 中检查错误或成功

python - Elasticsearch Python 客户端重新索引超时

python - 如何将非重叠数据帧矢量化为重叠移位数据帧?

python - 如何根据条件对 pandas 数据框进行子集化

python - bar() 缺少 1 个必需的位置参数 : 'left'

python - 在 Python 中 session 终止时获取信号

python - 遍历元组以计算列表中的值

使用装饰器进行 python/django 日志记录