serhatdogan
serhatdogan

Reputation: 63

How to extract lists in Python?

'''
[[[[[[[[[[[[[[[[[[[[[[[[[[[[1]]]]]]]]]]]]]]]]]]]]]]]]]]]]
find 1
'''
key = 1
x = [[[[[[[[[[[[[[[[[[[[[[[[[[[[key]]]]]]]]]]]]]]]]]]]]]]]]]]]]

#len(x) -> 1 

Actually my question is simple, but i couldn't solve this problem... What should i use to solve it, i mean should i use recrusive functions or for loop ???

for i in range(len(x)):
    for j in range(len(x)):
        for k in range(len(x)):
            for _ in range(len(x)):
                for ... 

Upvotes: 0

Views: 93

Answers (4)

Jox
Jox

Reputation: 76

You can do that as follow using more_itertools

import more_itertools

key = 1
x = [[[[[[[[[[[[[[[[[[[[[[[[[[[[key]]]]]]]]]]]]]]]]]]]]]]]]]]]]

flattened_list = list(more_itertools.collapse(x))

print(flattened_list) # [1]

Upvotes: 2

Đorđe Radujković
Đorđe Radujković

Reputation: 21

You can also do it with type check

key = 1
x = [[[[[[[[[[[[[[[[[[[[[[[[[[[[key]]]]]]]]]]]]]]]]]]]]]]]]]]]]

def find_key(array):
    if type(array) is list:
        return find_key(array[0])
    return array

print(find_key(x))

Upvotes: 1

S.B
S.B

Reputation: 16486

Here is a non-recursive approach for your current structure:

def extract_list(l: list):
    while True:
        l = l.pop()
        if not isinstance(l, list):
            return l


x = [[[[[[[[[[[[[[[[[[[[[[[[[[[[1]]]]]]]]]]]]]]]]]]]]]]]]]]]]
print(extract_list(x))  # 1

Upvotes: 1

Jab
Jab

Reputation: 27485

You could do this a couple ways but here's a solution using recursion:

x = [[[[[[[[[[[[[[[[[[[[[[[[[[[[1]]]]]]]]]]]]]]]]]]]]]]]]]]]]

def find_num(l):
    if isinstance(inner := l[0], list):
        return find_num(inner)
    return inner

print(find_num(x))

1

Upvotes: 0

Related Questions