Sort sequence of numbers from a TXT file

Asked

Viewed 1,041 times

1

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

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’t import the first line of the file as a vector I named lista. Can someone help me, please?

  • Insert in your question the part of the file in question and also the part of the code that reads this file and turns into list.

  • fnands to import the first line of the file just insert: with open(r'FILE PATH') as f: first_line = f.readline()

3 answers

1

Assuming that your input file (arquivo.txt) be 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 capable of loading and sorting all the values contained in the file lines to 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

Exit:

[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]

1

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

What’s with no Python for?

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 so, just convert the values:

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

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

numeros.sort()

Thus, a function that returns the first row of a file in an orderly fashion 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 on Repl.it

0

Create the file:

inserir a descrição da imagem aqui

Code:

arquivo = open('C:/Users/Usuario/Desktop/numeros.txt','r'); #Abre arquivo no modo 'read'.

linha = arquivo.readline() #lê uma linha do arquivo

arquivo.close() #Fecha o arquivo

lista = 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)

Exit:

inserir a descrição da imagem aqui

Browser other questions tagged

You are not signed in. Login or sign up in order to post.