Home > Software design >  How to print lines of list without square brackets and commas?
How to print lines of list without square brackets and commas?

Time:01-08

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?

CodePudding user response:

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

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

CodePudding user response:

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...

  • Related