如何在不分割字符串的情况下展平列表?

我想拼合可能包含其他列表的列表,但不要弄乱字符串。例如:


In [39]: list( itertools.chain(*["cat", ["dog","bird"]]) )

Out[39]: ['c', 'a', 't', 'dog', 'bird']

我想


['cat', 'dog', 'bird']


慕仙森
浏览 416回答 3
3回答

qq_笑_17

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

largeQ

对orip的答案进行了轻微修改,避免了创建中间列表:import itertoolsitems = ['cat',['dog','bird']]itertools.chain.from_iterable(itertools.repeat(x,1) if isinstance(x,str) else x for x in items)

翻过高山走不出你

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 Mdef flatten(L):    return [i for i in squash(L) if i!= []]>> flatten(["cat", ["dog","bird"]])['cat', 'dog', 'bird']希望这可以帮助
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python