Python交换方法不工作

2024-10-01 02:30:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试为python创建一个bubble排序方法,只针对pops和grins。但我不认为我的交换方法有效。在

def bubbleSort(list):
length = len(list)
for i in range(length - 1):
    if list[i] > list[i+1]:
        #swap
        swap(list[i], list[i+1])
        print(list)
print(list)

def swap(s1, s2):
    # assert type(s1) == list and type(s2) == list
    # tmp = s1[:]
    # s1[:] = s2
    # s2[:] = tmp
    s2, s1 = s1, s2

程序会显示出我的列表,但每次都不会有任何改变,这说明我的交换方法不起作用。在


Tags: 方法排序deftypelengthtmplistprint
1条回答
网友
1楼 · 发布于 2024-10-01 02:30:43

If you pass immutable arguments like integers, strings or tuples to a function, the passing acts like call-by-value. The object reference is passed to the function parameters. They can't be changed within the function, because they can't be changed at all, i.e. they are immutable. It's different, if we pass mutable arguments. They are also passed by object reference, but they can be changed in place in the function. If we pass a list to a function, we have to consider two cases: Elements of a list can be changed in place, i.e. the list will be changed even in the caller's scope. If a new list is assigned to the name, the old list will not be affected, i.e. the list in the caller's scope will remain untouched.

严格地说,在您的示例中,将list元素传递到swap函数中不会有效果。使用python语法可以直接编写:

list[i], list[i+1] = list[i+1], list[i]

不知道把这么小的逻辑提取成单独的函数的目的是什么。在

如需了解更多关于评估策略的信息,例如按值调用、按引用调用以及为什么不同,可以查看wiki。在

PPS。正如注释中正确指出的,python的常用评估策略是“Call-by-Sharing”,例如:

Call by sharing (also referred to as call by object or call by object-sharing) is an evaluation strategy first named by Barbara Liskov et al. for the language CLU in 1974.[5] It is used by languages such as Python,[6] Iota,[7] Java (for object references), Ruby, JavaScript, Scheme, OCaml, AppleScript, and many others. However, the term "call by sharing" is not in common use; the terminology is inconsistent across different sources. For example, in the Java community, they say that Java is call by value.[8] Call by sharing implies that values in the language are based on objects rather than primitive types, i.e. that all values are "boxed".

相关问题 更多 >