Фильтр по вложенности списков

Рейтинг: 0Ответов: 1Опубликовано: 04.05.2023

Есть список с такими данными:

['sum_for_pivot', '=', 1111]
['qwerty']
['PostCode', '!=', 'qwerty']
['PersonId']
['ID']

как его отфильтровать, чтобы получить:

['sum_for_pivot', '=', 1111]
['PostCode', '!=', 'qwerty']

Ответы

▲ 1

С использованием встроенной функции filter:

lists = [
         ['sum_for_pivot', '=', 1111],
         ['qwerty'],
         ['PostCode', '!=', 'qwerty'],
         ['PersonId'],
         ['ID']
]

def is_three_len(lst):
    return len(lst) == 3

results = filter(is_three_len, lists)
print(list(results))

Выводит:

[['sum_for_pivot', '=', 1111], ['PostCode', '!=', 'qwerty']]