2014-03-25 71 views
1

我經常使用此代碼unbunch名單和號碼列表|串是否有此代碼一個在線解決方案

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

通過Python的禪:「顯式優於隱式」。 – Bonifacio2

回答

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])] 
相關問題