0

I've checked the post and answers on the SO post Printing list elements on separated lines in Python, while I think my problem is a different one.

What I want is to transform:

lsts = [[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1]]

into the output like below:

[[1],
[1, 1],
[1, 2, 1],
[1, 3, 3, 1],
[1, 4, 6, 4, 1]]

I tried append, print in the for loop and "\n".join() but all failed.

Community
  • 1
  • 1
uniquegino
  • 1,841
  • 1
  • 12
  • 11

5 Answers5

0

Here's an adaptation of that same idea:

output = "[" + ",\n".join(str(i) for i in lsts) + "]"
Christian
  • 709
  • 3
  • 8
  • 1
    the `[]` in the `join()` are unnecessary. A generator expression is faster and more readable – Felk Apr 08 '16 at 03:34
0
print ']\n'.join(str(lsts).split('],'))

This is gross but does what you want it to.

for l in lsts:
    print l

almost does except you miss the first and last brackets. so you could do

list_len = len(lsts)
for i in range(list_len):
    if i == 0:
        print '['+str(lsts[i])
    elif i == list_len - 1:
        print str(lsts[i]( +']'
    else:
        print lists[i]
Sнаđошƒаӽ
  • 16,753
  • 12
  • 73
  • 90
quikst3r
  • 1,783
  • 1
  • 10
  • 15
0

Try this:

lsts = [[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1]]
print('[',end='')
for i,value in enumerate(lsts):
    print(value,end='')
    if i == len(lsts)-1:
        print(']')
    else:
        print(',')

Output:

[[1],
[1, 1],
[1, 2, 1],
[1, 3, 3, 1],
[1, 4, 6, 4, 1]]
Ren
  • 2,852
  • 2
  • 23
  • 45
0

You can try this if the form of lsts is fixed:

>>> print '['+'\n'.join([ str(i) for i in lsts ]) + ']'  

[[1]  
[1, 1]  
[1, 2, 1]  
[1, 3, 3, 1]  
[1, 4, 6, 4, 1]]  
Hoo Cui
  • 1
  • 2
0

To achieven exactly what you want, you could manually unroll and print the outer array like already suggested:

>>> lsts = [[1], [2,3], [4, 5, 6]]
>>> print("[" + ",\n".join(str(i) for i in lsts) + "]")
[[1],
[2, 3],
[4, 5, 6]]

Not exactly what you requested, but json.dumps can do some pretty-printing by specifying an indent:

>>> print(json.dumps(lsts, indent=4))
[
    [
        1
    ],
    [
        2,
        3
    ],
    [
        4,
        5,
        6
    ]
]

And then there's pprint, which is intended for somewhat intelligent printing for humans:

>>> pprint(lsts, width=20)
[[1],
 [2, 3],
 [4, 5, 6]]
Felk
  • 7,720
  • 2
  • 35
  • 65