Print a list of lists on separate lines

I have a list of lists:

a = [[1, 3, 4], [2, 5, 7]] 

I want the result to be in the following format:

 1 3 4 2 5 7 

I tried this as follows, but the outputs are not in the right shape:

 for i in a: for j in i: print(j, sep=' ') 

Outputs:

 1 3 4 2 5 7 

When changing the print call, use end instead of end :

 for i in a: for j in i: print(j, end = ' ') 

Outputs:

 1 3 4 2 5 7 

Any ideas?

+4
source share
4 answers

Iterate through each sub-list in the original list and unzip it in a print call with * :

 a = [[1, 3, 4], [2, 5, 7]] for s in a: print(*s) 

The default separation is set to ' ' , so there is no need to explicitly provide it. It means:

 1 3 4 2 5 7 

In your approach, you iterate over each item in each sub-list and print it individually. Using print(*s) , you unpack the list inside the print call, this essentially means:

 print(1, 3, 4) # for s = [1, 2, 3] print(2, 5, 7) # for s = [2, 5, 7] 
+8
source

Oneliner:

 print('\n'.join(' '.join(map(str,sl)) for sl in l)) 

Explanation:
you can convert list to str using the join function:

 l = ['1','2','3'] ' '.join(l) # will give you a next string: '1 2 3' '.'.join(l) # and it will give you '1.2.3' 

therefore, if you want to use linear characters, you must use a new line character.
But join only accepts a list of strings. To convert a list of things to a list of strings, you can use the str function for each item in the list:

 l = [1,2,3] ' '.join(map(str, l)) # will return string '1 2 3' 

And we apply this construct for every sl subexpression in the list l

+8
source

You can do it:

 >>> lst = [[1, 3, 4], [2, 5, 7]] >>> for sublst in lst: ... for item in sublst: ... print item, # note the ending ',' ... print # print a newline ... 1 3 4 2 5 7 
+2
source
 def print_list(s): for i in range(len(s)): if isinstance(s[i],list): k=s[i] print_list(k) else: print(s[i]) s=[[1,2,[3,4,[5,6]],7,8]] print_list(s) 

you can enter lists into lists inside lists ..... and yet everything will be printed as you expect.

0
source

All Articles