簡體   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