我有一个像这样的嵌套列表:
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]
将元组转换为字符,但不影响给定数组
答案 0 :(得分:3)
使用递归列表理解:
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'], ' ']]]