简体   繁体   中英

How to print lines of list without square brackets and commas?

So I have this problem where the program prints the lines of a list with the square brackets and commas.

lista=[]
f=open("eloadas.txt", "r")
for sor in f:
    sor=sor.strip().split()
    lista.append(sor)
lista.sort()
print("\n".join(map(str, lista)))

This is what I tried and the expected thing to happen was this:

1 1 32 Kovacs Lajos
1 10 30 Bolcskei Zsuzsanna
1 2 43 Kiss Peter

But instead of that, I got this:

['1', '1', '32', 'Kovacs', 'Lajos']
['1', '10', '30', 'Bolcskei', 'Zsuzsanna']
['1', '2', '43', 'Kiss', 'Peter']

Can someone please help me?

Instead of calling str on each inner map, you could join it with a space:

print("\n".join(map(lambda l : " ".join(l), lista)))

python has something called an "unpacking operator" - when used on a list, it will act as if the brackets are not there.

say x = [1, 2, 3] , *x will be as if I wrote 1, 2, 3 .

print can have arguments separated by commas.

these two features can be used together to get:

>>> x = [1, 2, 3, 4]
>>> print(*x)
1 2 3 4

if you want to print a list with no commas, use print(*listname)

this might go something like:

lista=[]
f=open("eloadas.txt", "r")
for sor in f:
    sor=sor.strip().split()
    lista.append(sor)
lista.sort()

for item in lista:
    print(*item)

but this is not the most efficient...

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