1

I am trying to print list lst using a single line of code

lst = [("A",23),("B",45),("C",88)]

print(*lst, sep="\n")

Output comes like this:

('A', 23)
('B', 45)
('C', 88)

What I am expecting is

A 23
B 45
C 88

However, this can be achieved by the following code

for i in range(len(lst)):
    print(*lst[i], sep=" ")

But I dont want to use a "for loop", rather to use * operator or any other technique to accomplish that in a single line of code

4

3 回答 3

1

You can achieve this in one line of code but it does involve a list comprehension (which you may consider a for loop):

print(*[' '.join([l[0], str(l[1])]) for l in lst], sep="\n")

Output:

A 23
B 45
C 88

Note we need to use str to convert the second value in the tuples in l into a string for join.

于 2020-01-21T06:05:57.270 回答
1

You could do it in one line like this:

print('\n'.join('{} {}'.format(*tup) for tup in lst))
于 2020-01-21T06:16:38.073 回答
0

Another way:

print(*map(lambda x: " ".join(x), lst), sep='\n', flush=True)
于 2020-08-02T21:55:00.363 回答