繁体   English   中英

Python,排序数字错误

[英]Python, sorting numbers error

def selectionSort(lst):
    with lst as f:
        nums = [int(line) for line in f]
    for i in range(len(nums) - 1, 0, -1):
       maxPos = 0
       for position in range(1, i + 1):
           if nums[position] > nums[maxPos]:
               maxPos = position

       value = nums[i]
       nums[i] = nums[maxPos]
       nums[maxPos] = value

def main():
    textFileName = input("Enter the Filename: ")
    lst = open(textFileName)
    selectionSort(lst)
    print(lst)

main()

好的,感谢hcwhsa帮助我处理了读取文件并将它们全部放在一行中。

当我运行该代码时,出现以下错误:

<_io.TextIOWrapper name='numbers.txt' mode='r' encoding='UTF-8'>

文本文件:

67
7
2
34
42

有什么帮助吗? 谢谢。

您应该从函数返回列表,并将其分配给变量,然后进行打印。

def selectionSort(lst):
    with lst as f:
        nums = [int(line) for line in f]
    ...
    ...
    return nums

sorted_lst = selectionSort(lst)
print(sorted_lst)

您的代码无效,因为您没有将列表对象传递给函数,而是传递了文件对象。 此版本的代码将列表传递给函数,因此在修改同一列表对象时不需要返回值:

def selectionSort(nums):

    for i in range(len(nums) - 1, 0, -1):
       maxPos = 0
       for position in range(1, i + 1):
           if nums[position] > nums[maxPos]:
               maxPos = position

       value = nums[i]
       nums[i] = nums[maxPos]
       nums[maxPos] = value


def main():
    textFileName = input("Enter the Filename: ")
    with open(textFileName) as f:
        lst = [int(line) for line in f]
    selectionSort(lst)
    print(lst)

main()

暂无
暂无

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

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