![](/img/trans.png)
[英]Manipulating every element in an n-level deep list of lists in python
[英]Unpacking n-level nested lists
假設我有一個清單,
[(1,2), (3, 4)].
如果列表中的所有元素都是元組,我將打印1 + 2和3 + 4。 但是,如果其中任何一個元素也是一個列表,則我向內部列表的每個元素加1,然后將該內部列表的每個元素附加到父列表。 例如。
list = [(1,2), [(3, 4), (5, 6)]],
變成
[(1, 2), (3, 4, 1), (5, 6, 1)].
同樣,如果內部列表將列表作為元素,則重復同樣的事情。 例如。
[(1,2), [(3, 4), (5, 6), [(7, 8)]]]
首先成為
[(1,2), [(3, 4), (5, 6), (7, 8, 1)]]
然后終於變成
[(1,2), (3, 4, 1), (5, 6, 1), (7, 8, 1, 1)].
我如何對這樣的列表執行此過程,該列表的嵌套級別(如列表中的列表中的列表...)是未知的?
我用來生成此列表的代碼如下:
def possible_sums(a):
if a == 2:
return [(1, 1)]
list_l = list(((a - 1, 1), ))
list_l.append(possible_sums(a-1))
return list_l
print(possible_sums(8))
該解決方案使用嵌套生成器。 我們遍歷列表中的項目,檢查其類型。 每當我們看到一個list
,我們都會在該列表上遞歸調用flatten
,並在每個輸出的末尾添加1
。 如果item
是一個元組,我們就產生它。 然后在flatten
之外,我們遍歷生成器以構建列表。
def flattener(lst):
for item in lst:
if isinstance(item, list):
gen = flattener(item)
for item in gen:
yield item + (1,)
elif isinstance(item, tuple):
yield item
print(list(flattener([(1,2), [(3, 4), (5, 6), [(7, 8)]], [(5, 6, 7), [(1, 2)]]])))
# [(1, 2), (3, 4, 1), (5, 6, 1), (7, 8, 1, 1), (5, 6, 7, 1), (1, 2, 1, 1)]
nested_lst = [(1,2), [(3, 4), (5, 6), [(7, 8)]] ,(2,3),[(6,7)]]
output = []
def de_nestify(lst,lvl):
if len(lst) != 0:
for item in lst:
if isinstance(item, list):
lvl += 1
de_nestify(item,lvl)
lvl = 0 #reset nesting lvl
else:
item += (1,)*lvl
output.append(item)
de_nestify(nested_lst,0)
print(output)
#[(1, 2), (3, 4, 1), (5, 6, 1), (7, 8, 1, 1), (2, 3), (6, 7, 1)]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.