Seungjun Lee
Seungjun Lee

Reputation: 13

Changing dimension of a list

d=[[[1],[1],[1]]]

There is a list like the one above.

I wanted the list to be [1,1,1].

d=[[[1],[1],[1]]]

print(np.shape(d))

d_1=[]

for item in d:

    d_1.extend(item)

print(d_1)

d_2=[]

for item in d_1:

    d_2.extend(item)

print(d_2)

>>>[1,1,1]

I did it like this but is there a more simple way?

Upvotes: 2

Views: 251

Answers (1)

user15801675
user15801675

Reputation:

How About this? You can use recursion, though it may exceed the recursion limit. In that case:

import sys
sys.setrecursionlimit(1500) #==== Set any number for the recursion limit

Here is the main code

d=[[[1],[1],[1]]]
new_l=[]
def check(lists:list):
    for i in lists:
        if not isinstance(i, list): #==== If it is not a list
            new_l.append(i)
            
        else:
            check(i) #=== Again iterate through the list
    return new_l
print(check(d))

Upvotes: 1

Related Questions