Output in two columns

1

The output of my code makes a list in a column.

Code:

path = '/home/allan/Área de trabalho/adjetivos.txt'
i = 0
lista = []
conta = 1
with open (path) as file_obj:
    ler = file_obj.readlines()
for le in ler:

    #print(le.rstrip())
    lista.append(le)

for i in lista:
    tam = len(lista)
    #print(tam)
    if i == lista[0]:
        print("1 ano: Bodas de "+str(i.title().rstrip()))
    elif i != lista[0]:
        conta = 1 + conta
        print(str(conta)+" anos: Bodas de "+i.title().rstrip())

Current output:

1 ano: Bodas de Ágata
2 anos: Bodas de Água-Marinha
3 anos: Bodas de Âmbar
4 anos: Bodas de Alabastro
5 anos: Bodas de Alexandrita
6 anos: Bodas de Amazônia
7 anos: Bodas de Ametista
8 anos: Bodas de Andaluzite
9 anos: Bodas de Aventurina
10 anos: Bodas de Axinite
...

... This is how it continues

I would like to "break the text", that the list would continue alongside as in the image:

HowcanIdoit?

fortextointextos:print(max(len(texto)))

WhycannotIhavethesameeffectofcountingthecharactersasyoudidusinglistcomp?Myinterpretationseeingthecodeworkinginpythontutoris2listitemsform1,Eg:"coffee", "sugar" - > "sugar coffee". It sounds magical, how can he include himself?
Here:
Is this how it happens? See below:   escritas[pos % linhas_coluna] would look like this:

...
[3 % 25]
[4 % 25]
[5 % 25]
...

So I would get the 3 and assign it to anos: Bodas de Âmbar (espaço de 25)

texto.ljust(tamanho, ' ') would be:

anos: Bodas de Âmbar (espaço de 25) , right?
I can not see this text going right, just to ljust (left) thus forming a single column!
Remembering: The program is working perfectly fine, but I do not reach the logic itself. How can he split into two if everything goes left ??

    
asked by anonymous 20.02.2018 / 03:57

1 answer

2

I would start by simplifying and making the code more Pythonic before even breaking for columns.

For this you can use list comprehensions to construct the list of adjectives as well as enumerate so you do not have to construct the positions manually:

path = '/home/allan/Área de trabalho/adjetivos.txt'
with open (path) as file_obj:
    ler = file_obj.readlines()

lista = [le.strip() for le in ler] #strip apenas na passagem para a lista
for pos,adjetivo in enumerate(lista):
    print("{} ano{}: Bodas de {}".format(pos+1, "" if pos == 0 else "s", adjetivo.title()))

To break into columns you can create a new list with the texts that would be written instead of just the adjectives that came from the file. Then create another list that corresponds to the rows of the columns, and pass each text to the corresponding row.

To organize and structure you can create a function that does this:

from math import ceil

def escrita_colunas(textos, colunas):
    linhas_coluna = ceil(len(textos) / colunas)
    tamanho = max([len(texto) for texto in textos]) + 1 #+1 para criar espaço entre colunas
    escritas = [''] * linhas_coluna

    for pos, texto in enumerate(textos):
        escritas[pos % linhas_coluna] += texto.ljust(tamanho, ' ')

    for escrita in escritas:
        print(escrita)

I used ljust to align each text to the left based on the highest tamanho of the various texts to be written, which will allow to create the visual alignment.

To put the text on the right line I used the modulo % operator. To better understand how this operator works we can start by considering the following code:

for i in range(15):
    print(i % 5)

Which produces the following result:

0
1
2
3
4
0
1
2
3
4
0
1
2
3
4

See for yourself at Ideone

Here we see when doing % 5 the number will always be between 0 and 4 and in a circular way. Applying to your example of 50 texts and 2 columns will give pos % 25 which will give you a number always between 0 and 24. It will be 0 to 24 for the first column and then again 0 to 24 for the second column.

After this, just build the texts to be written and call the function:

path = '/home/allan/Área de trabalho/adjetivos.txt'
with open (path) as file_obj:
    ler = file_obj.readlines()

lista = [le.strip() for le in ler]
textos = []
for pos,adjetivo in enumerate(lista):
    textos.append("{} ano{}: Bodas de {}".format(pos+1,"" if pos == 0 else "s",adjetivo.title()))

escrita_colunas(textos, 2)

View the writing function in columns working on Ideone

Edit :

Given that the function I wrote in columns was not clear to me, I decided to redo it as manual as possible, not using any native function, to see the whole process:

def escrita_colunas(textos, colunas):
    linhas_coluna = ceil(len(textos) / colunas)

    tamanho_max = 0 
    for texto in textos: #achar o tamanho do maior texto entre todos os textos
        tamanho = len(texto) + 1 #+1 para dar espaço entre colunas
        if tamanho > tamanho_max:
            tamanho_max = tamanho

    escritas = [''] * linhas_coluna #criar as colunas

    linha = 0 
    for texto in textos:
        #se chegou ao limite de linhas desta coluna volta a 0 para
        #"passar para a próxima coluna"
        if linha == linhas_coluna:
            linha = 0

        #quantos carateres faltam para chegar a quantidade de carateres da coluna
        carateres_faltam = tamanho_max - len(texto) 

        #colocar os carateres que faltam como espaços a seguir ao texto
        texto_inserir = texto + (' ' * carateres_faltam)

        escritas[linha] = escritas[linha] + texto_inserir
        linha = linha + 1

    for escrita in escritas:
        print(escrita)

See also this version of Ideone

    
20.02.2018 / 12:36