2012-10-01 24 views
1

問題內容: 通過過濾低位列表,創建至少5個字母長的單詞列表,其中的字母已按字母順序排列。在列表中理解一個字符串列表

我有什麼:

[word for word in lowers if len(word)>= 5 and word.sort=word] 

我知道,這是行不通的,因爲word.sort正在對一個字符串,並用字必須使此功能工作的列表。我如何在列表理解方面做到這一點,或者我需要定義之前的事情。

+0

即使'word'是一個列表,這仍然不起作用,因爲'sort'對列表進行破壞性排序並返回'None'。所以你需要使用'sorted'代替(或其他解決方案之一)。 – abarnert

+0

另外,你正在混合'='和'==',所以你會得到'SyntaxError'。 – abarnert

回答

1

最簡單的方法是使用列表理解:

[word for word in lowers if len(word)>=5 and sorted(word)==list(word)] 

另一種方法是使用Python 2的filter功能像這樣的東西。此外,這裏採用的string.join轉換排序列表返回字符串

#Lambda function to test condition 
test = lambda x: len(x)>=5 and ''.join(sorted(x))==x 
#Returns list of elements for which test is True 
filter(test, lowers) 

平原醇」功能(獎金:generatorsyield):

def filterwords(lst): 
    for word in lst: 
     if len(word)>=5 and sorted(word)==list(word): 
      yield word 

最後一個是最有效的,資源 - 明智之舉等。


更新:的.sort()可以在列表(而不是字符串)直接用來對列表排序,但它並沒有返回值。所以,list(word).sort()在這裏沒有用處;我們使用sorted(word)

>>> lst = [1,100,10] 
>>> sorted(lst) #returns sorted list 
[1, 10, 100] 
>>> lst #is still the same 
[1, 100, 10] 
>>> lst.sort() #returns nothing 
>>> lst #has updated 
[1, 10, 100] 
+1

+1,用於解釋所有可能性,每種可能性都有其優缺點。值得說明的是,即使「word」是一個「list」而不是一個「str」,「word.sort()」也不會起作用,但除此之外,它儘可能地完整,並且非常簡潔。 – abarnert

+0

謝謝你提及!我會更新我的答案。 –

2
>>> sorted('foo') == list('foo') 
True 
>>> sorted('bar') == list('bar') 
False 
相關問題