这行得通,但它对结构做了很多假设(即只有一层嵌套,string
仅限s)......
from itertools import chain
lst = ['alfa[1]', 'bravo', ('charlie[7]', 'delta[2]'), 'echo[3]']
flattened = chain.from_iterable([x] if isinstance(x, str) else x for x in lst)
result = [x.rsplit('[', 1)[0] for x in flattened]
当您为重点操作命名时,它会变得更加整洁:
def flatten(it):
return chain.from_iterable([x] if isinstance(x, str) else x for x in lst)
def clean(it):
return (x.rsplit('[', 1)[0] for x in it)
result = list(clean(flatten(lst)))
如果你想更接近你拥有的代码,你可以使用递归来清理它。
def process(lst, result=None):
if result is None:
result = []
for item in lst:
if isinstance(item, str):
result.append(item.rsplit('[', 1)[0])
else:
process(item, result)
return result
result = process(lst)
编辑
感谢@yoonkwon 的启发,更简洁,但请注意,compiler.ast
它已被弃用,并且在 Python 3 中不再存在:
from compiler.ast import flatten
result = [item.rsplit('[', 1)[0] for item in flatten(lst)]