Python, sorting numbers

2024-05-14 08:34:43 发布

您现在位置:Python中文网/ 问答频道 /正文

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

有什么帮助吗?谢谢。你知道吗


Tags: inforvaluemaindefaswithline
1条回答
网友
1楼 · 发布于 2024-05-14 08:34:43

您应该从函数返回列表并将其赋给变量,然后打印它。你知道吗

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

sorted_lst = selectionSort(lst)
print(sorted_lst)

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

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()

相关问题 更多 >

    热门问题