Home > Blockchain >  How to extract lists in Python?
How to extract lists in Python?

Time:11-01

'''
[[[[[[[[[[[[[[[[[[[[[[[[[[[[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 ... 

CodePudding user response:

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]

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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
  • Related