在本地范围内生成新列表并将其分配给全局范围内的变量

Genereating new list inside local scope and assigning it to a variable in global scope

大家好。是否可以在函数定义中修改列表并将新列表分配给全局范围内的变量。比如我不喜欢图6:

list = [1,2,3,4,5,6,7,8,9]
def modification(data):
    new_sexy_list = []
    for index in data:
        if index == 6:
            del index
    return **???????????????**

output
modification(list)
list = [1,2,3,4,5,7,8,9]

return语句怎么可能看起来像?

您可以在函数内改变列表:

li = [1,2,3,4,5,6,7,8,9]

def modification(data):
    data.pop(6)  # remove element at index 6

modification(li) 
print(li)  # will print [1, 2, 3, 4, 5, 6, 8, 9]

请注意,不需要 return 任何东西。

另一种可能性是在函数内部构建一个新列表并return它。

如果您不明白这是如何工作的,我强烈建议您阅读 https://nedbatchelder.com/text/names.html。 Python 名称(参考)和值与许多其他语言的工作方式不同。文章解释的很好