0

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

1
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'
Sign up to request clarification or add additional context in comments.

Comments

0

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

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

0
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

While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value. Please read this how-to-answer for providing quality answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.