繁体   English   中英

Python3:从文件中读取并对值进行排序

[英]Python3: read from a file and sort the values

我有一个txt文件包含以下方式的数据:

13
56
9
32
99
74
2

不同文件中的每个值。 我创建了三个功能:

第一个是交换值

def swap(lst,x,y):
    temp = lst[x]
    lst[x] = lst[y]
    lst[y] = temp

第二个功能是对值进行排序:

def selection_sort(lst):
    for x in range(0,len(lst)-1):
        print(lst)
        swap(lst,x,findMinFrom(lst[x:])+ x)

第三个功能是从列表中找到最小值:

def findMinFrom(lst):
    minIndex = -1
    for m in range(0,len(lst)):
        if minIndex == -1:
            minIndex = m
        elif lst[m] < lst[minIndex]:
            minIndex = m
    return minIndex

现在,我如何从包含数字的文件中读取并打印出它们的排序?

提前致谢!


我用了:

def main():
    f = []
    filename = input("Enter the file name: ")
    for line in open(filename):
        for eachElement in line:
            f += eachElement
    print(f)
    selectionSort(f)
    print(f)
main()

但还是不行! 任何帮助?

优秀的程序员不会重新发明轮子并使用大多数现代语言中标准的排序例程。 你可以做:

with open('input.txt') as fp:
    for line in sorted(fp):
        print(line, end='')

打印按字母顺序排列的行(作为字符串)。

with open('input.txt') as fp:
    for val in sorted(map(int, fp)):
        print(val)

按数字排序。

要读取文件中的所有行:

f = open('test.txt')
your_listname = list(f)

排序和打印

selection_sort(output_listname)
print(output_listname)

在排序/打印之前,您可能需要删除换行符

stripped_listname=[]
for i in your_listname:
    i = i.strip('\n')
    stripped_listname.append(i)

您可能还希望从排序函数中取出print语句,以便在排序时不会多次打印列表。

暂无
暂无

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

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