这段代码是否有一行解决方案

时间:2014-03-25 17:01:32

标签: python list

我经常使用此代码取消列表列表和数字|字符串

def deKnot(someList):
    l = []
    for each in someList: l.extend(each) if (hasattr(each,"__iter__")) else l.append(each)
    return each

我希望我能使用像......这样的语法。

def deKnot(someList): return [extend(each) if (hasattr(each,"__iter__")) else append(each) for each in someList]

哪个不起作用。这个问题是否有单行解决方案?

1 个答案:

答案 0 :(得分:4)

def deKnot(someList):
    return [e 
            for each in someList 
            for e in (each if hasattr(each, '__iter__') else [each])]

each 转换为一个可迭代的并始终循环;而不是.extend()在列表推导中使用嵌套循环。

您可以使用collections.Iterable代替属性检查:

from collections import Iterable

def deKnot(someList):
    return [e 
            for each in someList 
            for e in (each if isinstance(each, Iterable) else [each])]