Python如何将列表作为参数并编辑其值? [英] Python how to take a list as a parameter and edit its values?

查看:106
本文介绍了Python如何将列表作为参数并编辑其值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

def radixSort(A):

    #get max amount of digits

    A = sortByDigit(A, maxDigits) #this works
    print(A) #prints A as sorted

if __name__ == "__main__":
    A = [int(100*random.random()) for i in range(10)]
    radixSort(A)
    print(A) #prints unsorted

为什么在radixSort中更改A不会在main方法中更改A?我意识到我可以简单地在radixSort中添加return语句,并在main方法中添加赋值语句,但是代码必须通过以下测试用例:

Why does changing A in radixSort not change A in the main method ? I realize I could simply add a return statement in radixSort, and an assignment statement in the main method, but the code has to pass the following test case:

    def testrRadixSort(self):
        A = [4, 3, 2]
        radixSort(A)
        self.assertEqual(A, [4,3,2])

推荐答案

sortByDigit不在适当的位置排序.它正在创建一个新列表并返回对该列表的引用.

sortByDigit isn't sorting inplace. It's creating a new list and returning a reference to that.

您可以通过此简单更改将A的内容替换为新列表的内容

You can replace the contents of A with the content of the new list with this simple change

A[:] = sortByDigit(A, maxDigits) #this works

或者,您可以修改sortByDigit,以便它可以就位排序

Alternatively you could modify sortByDigit so it does sort inplace

这篇关于Python如何将列表作为参数并编辑其值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆