我经常使用此代码取消列表列表和数字|字符串
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]
哪个不起作用。这个问题是否有单行解决方案?
答案 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])]