3 回答

TA贡献1818条经验 获得超7个赞
def flatten(foo):
for x in foo:
if hasattr(x, '__iter__'):
for y in flatten(x):
yield y
else:
yield x
(__iter__与Python中几乎所有其他可迭代对象不同,字符串实际上实际上没有属性。但是请注意,这在Python 3中有所变化,因此上述代码仅在Python 2.x中有效。)
适用于Python 3.x的版本:
def flatten(foo):
for x in foo:
if hasattr(x, '__iter__') and not isinstance(x, str):
for y in flatten(x):
yield y
else:
yield x

TA贡献2039条经验 获得超7个赞
对orip的答案进行了轻微修改,避免了创建中间列表:
import itertools
items = ['cat',['dog','bird']]
itertools.chain.from_iterable(itertools.repeat(x,1) if isinstance(x,str) else x for x in items)

TA贡献1875条经验 获得超3个赞
def squash(L):
if L==[]:
return []
elif type(L[0]) == type(""):
M = squash(L[1:])
M.insert(0, L[0])
return M
elif type(L[0]) == type([]):
M = squash(L[0])
M.append(squash(L[1:]))
return M
def flatten(L):
return [i for i in squash(L) if i!= []]
>> flatten(["cat", ["dog","bird"]])
['cat', 'dog', 'bird']
希望这可以帮助
添加回答
举报