简体   繁体   English

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

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

I have a txt file that contains data in the following fashion: 我有一个txt文件包含以下方式的数据:

13
56
9
32
99
74
2

each value in a different file. 不同文件中的每个值。 I created three function: 我创建了三个功能:

the first one is to swap the values 第一个是交换值

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

and the second function is to sort the values: 第二个功能是对值进行排序:

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

the third function is to find the minimum value from the list: 第三个功能是从列表中找到最小值:

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

Now, how can I read from the file that contains the numbers and print them sorted? 现在,我如何从包含数字的文件中读取并打印出它们的排序?

Thanks in advance! 提前致谢!


I used: 我用了:

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

but still not working! 但还是不行! any help? 任何帮助?

Good programmers don't reinvent the wheel and use sorting routines that are standard in most modern languages. 优秀的程序员不会重新发明轮子并使用大多数现代语言中标准的排序例程。 You can do: 你可以做:

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

to print the lines sorted alphabetically (as strings). 打印按字母顺序排列的行(作为字符串)。 And

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

to sort numerically. 按数字排序。

To read all the lines in a file: 要读取文件中的所有行:

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

To sort and print 排序和打印

selection_sort(output_listname)
print(output_listname)

You may need to strip newline characters before sorting/printing 在排序/打印之前,您可能需要删除换行符

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

You probably also want to take the print statement out of your sort function so it doesn't print the list many times while sorting it. 您可能还希望从排序函数中取出print语句,以便在排序时不会多次打印列表。

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

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