我試圖返回具有長度大小的單詞的元素。 單詞是一個列表,大小在這裏是一個正整數。 結果應該是這樣的。python-返回具有一定長度的列表元素
by_size(['a','bb','ccc','dd'],2] returns ['bb','dd']
def by_size(words,size)
for word in words:
if len(word)==size:
我不知道如何從這部分繼續。任何建議將是一個很大的幫助。
我試圖返回具有長度大小的單詞的元素。 單詞是一個列表,大小在這裏是一個正整數。 結果應該是這樣的。python-返回具有一定長度的列表元素
by_size(['a','bb','ccc','dd'],2] returns ['bb','dd']
def by_size(words,size)
for word in words:
if len(word)==size:
我不知道如何從這部分繼續。任何建議將是一個很大的幫助。
return filter(words, lambda x: len(x)==size)
假設您想稍後使用它們,那麼將它們作爲列表返回是個不錯的主意。或者只是打印到終端。這真的取決於你的目標。你可以去列表(或者其他變量名).append在if語句中來做到這一點。
def by_size(words,size):
result = []
for word in words:
if len(word)==size:
result.append(word)
return result
現在叫像下面
desired_result = by_size(['a','bb','ccc','dd'],2)
其中desired_result
將['bb', 'dd']
我覺得這很好。如果我想強制執行我的先決條件,即「文字是字符串列表,大小是一個正整數」,有什麼我需要修改? – shaarr 2014-11-02 09:07:06
是的,你可以執行你的前提條件,修改如下: **如果size> -1且isinstance(word,str):** – 2014-11-02 10:05:24
我會用一個列表理解函數:
def by_size(words, size):
return [word for word in words if len(word) == size]
+1,列表解析優先於使用排序,過濾器,映射和簡單循環。 – Lysergia25 2014-11-02 09:19:21
你的意思是這樣的:
In [1]:words = ['a','bb','ccc','dd']
In [2]:result = [item for item in len if(item)== 2]
在[3]:導致 出[3]: 'BB', 'DD']
的OP表示自己就是後他的問題 - 他要返回一個列表。 – Ben 2014-11-02 09:00:39