首页 > 解决方案 > 如果使用列表推导,为什么函数不会更新列表,但在使用 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"]

标签: python

解决方案


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)

推荐阅读