简体   繁体   English

Python:创建客户排序方法并在列表排序之前停止循环

[英]Python: creating customer sort method & loop stops before list sorted

I am trying to create a custom sort method in which I take a list that is not in numerical order and puts the list into order from lowest to highest. 我正在尝试创建一个自定义排序方法,在该方法中,我采用了一个未按数字顺序排列的列表,并将该列表按从最低到最高的顺序排列。

The program should take the following list... 该程序应采用以下列表...

arr = [1, 2, 3, 1, 4]

*and print it as follows...* *并按以下方式打印 ... *

arr = [1, 1, 2, 3, 4]

As it stands, my code reads... 就目前而言,我的代码显示为...

def sort(list):
for i in range(1, len(list)):
    if list[i] < list[i - 1]:
        temp = list[i - 1]
        list[i - 1] = list[i]
        list[i] = temp
        print arr       
sort(arr)

And my output is this... 我的输出是这个...

[1, 2, 1, 3, 4]

It seems as though the function runs through the list once, reorders the numbers once and stops before they are all in numerical order. 似乎函数一次在列表中运行一次,对数字重新排序一次,然后在它们全部按数字顺序停下来。 How do I make it run through the list as many times as it takes to put all of the numbers where they should be? 我如何使它遍历列表,将所有数字放在应有的位置?

Why won't you just: 你为什么不只是:

def sort_list(my_list):
    print sorted(my_list)


def main():
    arr = [1, 3, 2, 5, 4]
    sort_list(arr)

if __name__ == "__main__":
    main()

This will have the following output: 这将具有以下输出:

[1, 2, 3, 4, 5]

If you don't want to use a built-in function just do this: 如果您不想使用内置函数,请执行以下操作:

def sort_list(new_list):
    data_list = [1, 3, 2, 5, 4]

    while data_list:
        minimum = data_list[0]  # arbitrary number in list
        for x in data_list:
            if x < minimum:
                minimum = x
        new_list.append(minimum)
        data_list.remove(minimum)

    print new_list


def main():
    new_list = []
    sort_list(new_list)

if __name__ == "__main__":
    main()

This will have the same output: 这将具有相同的输出:

[1, 2, 3, 4, 5]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM