0
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

有什么帮助吗?谢谢。

4

1 回答 1

3

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

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()
于 2013-10-05T16:18:37.330 回答