Sujin
Sujin

Reputation: 273

how to remove the square bracket that are leftover in list with python?

I have generated the results into the list like this

In[11]: a

Out[11]: [[[1, 3, 2, 4], [1, 3, 2, 6]],
         [[2, 4], [2, 6]],
         [[3, 2, 4], [3, 2, 6]],
         [[4]],
         [[5, 4]],
         [[6]]]

but I would like to remove the square brackets that are leftover resulting as this

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

I have tried sum(a,[]) to reduce 1 dimension but the result is shown as follows

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

and tried np.squeeze(a) but the result is shown as follows

array([list([1, 3, 2, 4]), list([1, 3, 2, 6]), list([2, 4]), list([2, 6]),
       list([3, 2, 4]), list([3, 2, 6]), list([4]), list([5, 4]),
       list([6])], dtype=object)

any suggestions for aggregating this kind of list?

thank you in advance

Upvotes: 3

Views: 341

Answers (3)

Bindu
Bindu

Reputation: 29

str(a).replace('[[','[').replace(']]',']')

Upvotes: 0

Underoos
Underoos

Reputation: 5180

Try this.

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

fl = []
for i in a:
    for j in i:
        fl.append(j)

print fl

Upvotes: 2

Abhishek Kulkarni
Abhishek Kulkarni

Reputation: 1767

You can try this below :

    a = [[[1, 3, 2, 4], [1, 3, 2, 6]],
         [[2, 4], [2, 6]],
         [[3, 2, 4], [3, 2, 6]],
         [[4]],
         [[5, 4]],
         [[6]]]
    output = [elem for output_list in a for elem in output_list]
    print(output)

Upvotes: 4

Related Questions