I'm looking for a way to print a multidimensional lists in a specific way. This is how my list full of int looks.
[[1,2,3],[4,5,6]]
or
[[1,2,3,4,5,6]]
I want to print each element with a space and a comma between the two 'big' elements in the list. So for my example the output would be:
1 2 3, 4 5 6
and
1 2 3 4 5 6
I use python 3.4.2
4 Answers 4
In [78]: L = [[1,2,3],[4,5,6]]
In [79]: ', '.join([' '.join([str(i) for i in subl]) for subl in L])
Out[79]: '1 2 3, 4 5 6'
In [80]: L = [[1,2,3,4,5,6]]
In [81]: ', '.join([' '.join([str(i) for i in subl]) for subl in L])
Out[81]: '1 2 3 4 5 6'
Comments
Strings can be easily joined using 'sep'.join(...) with sep being the separator. Before joining the numbers of one part of the array, you need to convert them to strings. This can be easily done using a map function. For each element in i it applies the str function. After joining the numbers of each part separated with a space, you can join the parts to the final result.
l = [[1,2,3],[4,5,6]]
print ', '.join([' '.join(map(str, i)) for i in l])
Output:
1 2 3, 4 5 6
Note: In Python 3 you need to call print with brackets: print(...).
Comments
>>> l = [[1, 2, 3], [4, 5, 6]]
>>> ', '.join(map(lambda x: ' '.join(map(str, x)), l))
'1 2 3, 4 5 6'
>>> l = [[1, 2, 3, 4, 5, 6]]
>>> ', '.join(map(lambda x: ' '.join(map(str, x)), l))
'1 2 3 4 5 6'
Comments
ls = [[1, 2, 3, 4], [5, 6, 7, 8]]
for n in range(0, len(ls)):
for m in range(0, len(ls[n])):
print(str(ls[n][m]) + ' ', end='')
if n < (len(ls)-1):
print(', ', end='')
else:
print('')
1 Comment
Explore related questions
See similar questions with these tags.