3

Появилась такая проблема, мне нужно распаковать многомерный список с заданной глубиной.

Допустим у меня есть список my_list = [1, [2, 3],[[4]]] и параметр глубины depth = 1, на вывод получаем [1, 2, 3, [4]],

если depth = 2 то [1, 2, 3, 4].

Как это все реализовать в функции?

P.s импортировать ничего нельзя

def unpack(my_list: list, depth: int = 0):

4 ответа 4

4
def flatten(value, depth):
    if depth and isinstance(value, list):
        for v in value: yield from flatten(v, depth - 1)
    else: yield value

a = [1, [2, 3],[[4]]]
print(list(flatten(a, 2)))  # [1, 2, 3, [4]]
print(list(flatten(a, 3)))  # [1, 2, 3, 4]
3
def flatten(ls, depth):
  flattenList = []
  def unpack(ls, currentDepth):
    nonlocal flattenList
    for member in ls:
      if isinstance(member, list) and depth >= currentDepth:
        unpack(member, currentDepth + 1)
      else:
        flattenList.append(member)
  unpack(ls, 1)
  return flattenList

ls = [1, [2, 3],[[4]]]

print(flatten(ls, 2))
print(flatten(ls, 1))

Я решил задачу вот так

1
  • Спасибо больше.
    – Дима
    13 мая 2020 в 19:12
2

Итеративное решение.

my_list = [1, [2, 3],[[4]]]

def unpack(my_list: list, depth: int = 0): 
    while depth:
        tmp_list = []
        for item in my_list:
            if isinstance(item, list):
                tmp_list.extend(item)
            else:
                tmp_list.append(item)

        my_list = tmp_list
        depth -= 1

    return my_list

print(unpack(my_list, 1)) 
print(unpack(my_list, 2))

Output

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

UPD: Не увидел что нельзя импортировать :(

from functools import reduce

data =  [1, [2, 3], [[4]]]

def flatten(ls,depth):
    def _(carry,item):
        next_item = flatten(item, depth-1) if isinstance(item, list) and depth > 0 else [item]
        return carry + next_item
    return reduce(_, ls, [])

print(flatten(data,0))
print(flatten(data,1))
print(flatten(data,2))
print(flatten(data,3))

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.