python排序中不可更改的输入变量的问题

时间:2014-01-27 21:54:51

标签: python

我正在编写一系列不同种类的python方法。我所拥有的是用户输入的数字,我将其变成一个列表。然后我在输入列表上运行我的bubble_sort方法,然后打印结果。我保存了我的初始输入列表,以便我可以使用selection_sort重新排序,但是当我打印出原始列表时,我正在打印bubble_sorted列表。我是python的新手,所以我不确定我是否缺少关于语言变量的基本概念。这是我的代码

def listify(i):
    temp_list = []
    input_list_local = []
    input_list_local = list(i)
    for char in input_list_local:
        if char.isdigit():
            temp_list.append(char)
    return temp_list


def bubble_sort(input):
    for i in range(len(input)-1):
        for j in range(len(input)-1):
            if(input[j] > input[j+1]):
                tmp = input[j]
                input[j] = input[j+1]
                input[j+1] = tmp
    return input

def selection_sort(input):
    pass


input = raw_input("enter random numbers here seperated by spaces-> ")
print("you entered "+input)
input_list = listify(input)
print(input_list)
pass_list = input_list
print(bubble_sort(pass_list))
print(input_list) #should print original input list.  Instead prints sorted list

1 个答案:

答案 0 :(得分:4)

您正在修改相同的列表:pass_list = input_list表示pass_list只是同一列表对象的不同名称。因此,在调用bubble_sort(pass_list)之后,您已经修改了pass_list,还修改了input_list,因为它们是同一个对象(在内存中)。因此,当您打印input_list时,您会看到已排序的列表。

您可以通过执行以下操作来解决此问题:

pass_list = input_list[:]

这会使用Python's slicing notation复制input_list。然后,您可以安全地对pass_list进行排序,但不会影响原始input_list