Python中的自定义排序方法无法正确排序列表

Python中的自定义排序方法无法正确排序列表

本文介绍了Python中的自定义排序方法无法正确排序列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是计算机班的学生,我们必须编写一个包含文件处理和排序的程序.我已经完成了文件处理,并写出了我的排序(这是一个简单的排序),但是它没有对列表进行排序.我的代码是这样的:

I'm a student in a Computing class and we have to write a program which contains file handling and a sort. I've got the file handling done and I wrote out my sort (it's a simple sort) but it doesn't sort the list. My code is this:

namelist = []
scorelist = []
hs = open("hst.txt", "r")
namelist = hs.read().splitlines()
hss = open("hstscore.txt","r")
for line in hss:
    scorelist.append(int(line))




scorelength = len(scorelist)
for i in range(scorelength):
    for j in range(scorelength + 1):
        if scorelist[i] > scorelist[j]:
            temp = scorelist[i]
            scorelist[i] = scorelist[j]
            scorelist[j] = temp
            return scorelist

我使用Python已有很长时间了,所以我知道代码可能效率不高,但是我真的不想使用完全不同的方法对它进行排序,所以我们不允许使用.sort()或.sorted(),因为我们必须编写自己的排序函数.我在做错什么吗?

I've not been doing Python for very long so I know the code may not be efficient but I really don't want to use a completely different method for sorting it and we're not allowed to use .sort() or .sorted() since we have to write our own sort function. Is there something I'm doing wrong?

推荐答案

def super_simple_sort(my_list):
    switched = True
    while switched:
        switched = False
        for i in range(len(my_list)-1):
            if my_list[i] > my_list[i+1]:
               my_list[i],my_list[i+1] = my_list[i+1],my_list[i]
               switched = True

super_simple_sort(some_list)
print some_list

是一个非常简单的排序实现...对您来说是等效的,但是利用了一些东西来加快它的速度(我们只需要一个for循环,只要列表不按顺序就只需要重复一次即可. ,而且python不需要temp var来交换值)

is a very simple sorting implementation ... that is equivelent to yours but takes advantage of some things to speed it up (we only need one for loop, and we only need to repeat as long as the list is out of order, also python doesnt require a temp var for swapping values)

由于它更改了实际的数组值,您实际上甚至不需要返回

since its changing the actual array values you actually dont even need to return

这篇关于Python中的自定义排序方法无法正确排序列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 03:58