简体   繁体   中英

Print list of list using list comprehension

List 'a' can be printed as follows (CODE1):

a = [[4, 5], [2, 6]] 
print(*a, sep='\n')

The output (OP1) is:

[4, 5]
[2, 6]

I want the sublists to be printed in tab separated form. This can be done using loop as follows (CODE2):

for b in a:
print(*b, sep='\t')

Its output (OP2) is:

4   5
2   6

Can I get OP2 by modifying CODE1? I think list comprehension would be one of the routes of achieving this.


Questions referred

You can use str.join with generator expressions:

print('\n'.join(' '.join(str(i) for i in l) for l in a))

This outputs:

4 5
2 6

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