[英]Converting nested list of tuples to nested list of first element from tuples
我有一個像這樣的嵌套列表:
a = [([('m', 2), ([('o', 1), ([('k', 1), ('h', 1)], 2)], 3)], 5),
([('e', 3), ([([('t', 1), ('a', 1)], 2), (' ', 2)], 4)], 7)]
我想擺脫每個元組中的第二個元素,因此列表只會成為字符列表。 像那樣:
[['m', ['o', ['k', 'h']]], ['e', [['t', 'a'], ' ']]]
我嘗試過以下方法:
def transform(array):
for x in array:
if type(x[0]) is list:
transform(x[0])
else:
x = x[0]
它將元組轉換為字符,但它不會影響給定的數組
使用遞歸列表理解:
def recursive_strip(my_list):
"""Recursively remove the second element from nested lists of tuples."""
return [
recursive_strip(one) if isinstance(one, list) else one
for one, two in my_list
]
在示例上運行此代碼,我們得到:
a = [([('m', 2), ([('o', 1), ([('k', 1), ('h', 1)], 2)], 3)], 5),
([('e', 3), ([([('t', 1), ('a', 1)], 2), (' ', 2)], 4)], 7)]
result = recursive_strip(a)
result
是:
[['m', ['o', ['k', 'h']]], ['e', [['t', 'a'], ' ']]]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.