这是一个嵌套版本
li = ['0', ['1', '2'], ['3', ['4', '5'], '6', ['7'], '8'], '9']
def to_int(lst, path=[]):
for i, j in enumerate(lst):
if isinstance(j, list):
yield list(to_int(j, path+[i]))
else:
yield int(j), path+[i]
print(list(to_int(li)))
还有一个扁平化版本(Python3.3+)
li = ['0', ['1', '2'], ['3', ['4', '5'], '6', ['7'], '8'], '9']
def to_int(lst, path=[]):
for i, j in enumerate(lst):
if isinstance(j, list):
yield from to_int(j, path+[i])
else:
yield int(j), path+[i]
for item in to_int(li):
print (item)
如果不能使用yield from
(< Python3.3),就得写这种繁琐的方式
li = ['0', ['1', '2'], ['3', ['4', '5'], '6', ['7'], '8'], '9']
def to_int(lst, path=[]):
for i, j in enumerate(lst):
if isinstance(j, list):
for item in to_int(j, path+[i]): yield item
else:
yield int(j), path+[i]
for item in to_int(li):
print (item)
请注意,将空列表作为默认参数通常是一个坏主意,但在这里我们注意不要对其进行变异,所以没关系。