Sort sequence numbers from a TXT file

1

I have a TXT file with numbers separated by spaces and I want to sequence from the smallest number to the largest, only the numbers on the first line of that file. The sequencing logic I believe I have achieved:

tam_entrada = len(lista)

for i in range (tam_entrada):
    for j in range (1, tam_entrada-i):
        if lista[j] < lista[j-1]:
            lista[j], lista[j-1] = lista[j-1], lista[j]


print(lista)

But I can not import the first line of the file as a vector that I named lista . Can someone help me, please?

    
asked by anonymous 03.07.2018 / 04:47

3 answers

1

To work with files, I advise you to use context managers:

What is with in Python?

with open('arquivo.txt') as arquivo:
    linha = arquivo.readline()

However, linha will be a string and to sort, it will be interesting to have a list of numbers. To do this, simply convert the values:

numeros = [int(numero) for numero in linha.split()]

And the ordering itself can be done with the sorted native function or with the sort method of the list:

numeros.sort()

So, a function that returns the first line of a file in an ordered way would be:

def linha_ordenada(caminho):
    with open(caminho) as arquivo:
        linha = arquivo.readline()
    numeros = [int(numero) for numero in linha.split()]
    numeros.sort()
    return numeros

See working at Repl.it

    
03.07.2018 / 13:31
1

Assuming your input file ( arquivo.txt ) is something like:

9 8 7 6 5 4 3 2 1
5 3 1 9 7 5 9 8 1
3 4 5 8 3 0 1 0 0
1 2 3 3 2 1 10 11 12
6 3 8 15 20 1 4 2 9

You can implement a function that can load and sort all the values contained in the rows of the file into a two-dimensional list:

def obter_linhas_ordenadas( arq ):
    with open(arq) as arquivo:
        lst = []
        for linha in arquivo:
            lst.append(sorted([int(n) for n in linha.split()],key=lambda x:x))
    return lst;

lista = obter_linhas_ordenadas( 'arquivo.txt' );

print(lista[0])  # Exibe Linha 1
print(lista[2])  # Exibe Linha 3
print(lista[4])  # Exibe Linha 5

Output:

[1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 0, 0, 1, 3, 3, 4, 5, 8]
[1, 2, 3, 4, 6, 8, 9, 15, 20]
    
03.07.2018 / 18:51
0

Create the file:

Code:

arquivo=open('C:/Users/Usuario/Desktop/numeros.txt','r');#Abrearquivonomodo'read'.linha=arquivo.readline()#lêumalinhadoarquivoarquivo.close()#Fechaoarquivolista=linha.split(" ") #Cria uma lista separando por " " (espaço) Ex.: "1 2 3".split(" ") == ['1','2','3']

tam_entrada = len(lista)

for i in range (tam_entrada):
    for j in range (1, tam_entrada-i):
        if lista[j] < lista[j-1]:
            lista[j], lista[j-1] = lista[j-1], lista[j]
print(lista)

Output:

    
03.07.2018 / 13:05