2012-05-19 88 views

回答

7

我的解決辦法是簡單明瞭:

result = [] 
for x in a: 
    if isinstance(x, list) and len(x) == 1: # check item type and length 
     result.append(x[0]) 
    else: 
     result.append(x) 

還是相同的,但一個行

>>> [x[0] if isinstance(x, list) and len(x) == 1 else x for x in a] 
[3, 4, 1, 8, 9, [3, 4, 5]] 
+0

謝謝,成功了! –

+2

@Levon它與'map(lambda x:x [0] if isinstance(x,list)和len(x)== 1 else x,a)'是一樣的。 –

+1

@Not_a_Golfer我知道(和列表理解:-),這個解決方案是優雅的,所以我upvote。我只是認爲,如果答案不僅僅包含簡短的解決方案代碼,以防某些讀者不太熟悉解決問題的更多pythonic方法,那麼答案會更有用。我發現答案現在以有用的方式得到了增強。都很好。 – Levon

相關問題