简体   繁体   中英

How to display the last element using join python

python's join method ignores the last element in the list, but I want to be able to display without problems, look at my code:

import re
estoque = [0,1,20,0]                      
estoque_formated = '\n'.join([str(elem) for elem in estoque])
tamanho = [20, 34, 34.5, 40]                    
joined = f' Em estoque: {estoque_formated[0]}\n'.join(["Tamanho: " + str(elem) for elem in tamanho])                                            
print(joined)

The output of the script I want is this:

 Tamanho: 20 Em estoque 0
 Tamanho: 34 Em estoque 1
 Tamanho: 34.5 Em estoque 20
 Tamanho: 40 Em estoque 0

Obs , notice that the sizes are displayed, but it always takes the index 0 of the variable estoque_formated how can I get the first index and add it? Example starting from 0 and going to 1 then 2...etc? Well, I need to solve the problem with the index as I said, and to get it I was able to display the size and value of the estoque_formated variable even though it's the last element, I want to modify the script as little as possible.

Ok, so you only need to join the resulting strings right at the end. You need zip() to pair up items from two different lists:

estoque = [0,1,20,0]                      
tamanho = [20, 34, 34.5, 40]                    

joined = [f'Tamanho: {t} Em estoque: {s}' for t,s in zip(tamanho,estoque)]
print('\n'.join(joined))

Output as requested (moved the '\\n' )

Why use join when you could just iterate over the two lists and print as you need.

estoque = [0,1,20,0]                      
tamanho = [20, 34, 34.5, 40]                    

for i in range(4):
    print(f'Tamanho: {tamanho[i]}\tEm estoque: {estoque[i]}')

Output:

Tamanho: 20 Em estoque: 0
Tamanho: 34 Em estoque: 1
Tamanho: 34.5   Em estoque: 20
Tamanho: 40 Em estoque: 0

You could just write

estoque = [0, 1, 20, 0]
tamanho = [20, 34, 34.5, 40]
print(*(f"Tamanho: {t} Em estoque: {e}" for t, e in zip(tamanho, estoque)), sep="\n")

To get a properly padded output you could format the values accordingly:

print(*(f"Tamanho: {t:4} Em estoque: {e:2}" for t, e in zip(tamanho, estoque)), sep="\n")

which would result in

Tamanho:   20 Em estoque:  0
Tamanho:   34 Em estoque:  1
Tamanho: 34.5 Em estoque: 20
Tamanho:   40 Em estoque:  0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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