选择排序程序python [英] Selection sort program python

查看:81
本文介绍了选择排序程序python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以这应该是一个排序程序,但是由于某种原因,它不是对我提供的文件进行排序,而只是给我直接的数字.任何帮助,将不胜感激.谢谢

So this is supposed to be a sorting program, but for some reason, it is not sorting the file I'm giving, but just giving me straight numbers as it is. Any help would be appreciated. Thank you

filename=input('Enter file path:')
file = open(filename, 'r')
alist = [(line) for line in file.readlines()]
print(alist)

def selectionSort(alist):
    for index in range(0, len(alist)):
        ismall = index
        for i in range(index,len(alist)):
            if alist[ismall] > alist[i]:
                ismall = i
        alist[index], alist[ismall] = alist[ismall], alist[index]
    return alist 

推荐答案

您没有调用该函数!

def selectionSort(alist):
    for index in range(0, len(alist)):
        ismall = index
        for i in range(index,len(alist)):
            if alist[ismall] > alist[i]:
                ismall = i
        alist[index], alist[ismall] = alist[ismall], alist[index]

filename=input('Enter file path:')
file = open(filename, 'r')
alist = file.readlines()

# Call the function!
selectionSort(alist)
print(alist)

您已经告诉Python selectionSort是什么意思,但是您没有告诉它对任何内容进行排序.您需要调用selectionSort(alist)才能真正执行排序.

You've told Python what selectionSort means, but you haven't told it to sort anything. You need to call selectionSort(alist) to actually perform the sort.

此外,您希望列表排序的顺序很可能不是您告诉Python对其进行排序的顺序.alist是一个字符串列表,因此,您要告诉Python使用字典比较订购清单.如果应该将其视为整数,则需要将数据转换为整数:

Also, the order you want the list to be sorted in is most likely not the order you're telling Python to sort it in. alist is a list of strings, so you're telling Python to use lexicographic comparison to order the list. If it's supposed to be treated as, say, integers, you need to convert the data to integers:

alist = [int(line) for line in file]

(此外,由于selectionSort会修改其操作的列表,因此最好不要返回该列表.如果返回它,则给人的印象是它会创建一个新的排序列表.)

(Also, since selectionSort modifies the list it operates on, it's best not to return the list. If you return it, it gives the impression that it creates a new, sorted list.)

这篇关于选择排序程序python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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