words = ['apple', 'orange', 'pear', 'milk', 'otter', 'snake','iguana','tiger','eagle']
vowel=[]
for vowel in words:
if vowel [0]=='a,e':
words.append(vowel)
print (words)
我的代碼不正確,它會打印出原始列表中的所有單詞。如何用Python找出列表中以元音開頭的單詞?
words = ['apple', 'orange', 'pear', 'milk', 'otter', 'snake','iguana','tiger','eagle']
vowel=[]
for vowel in words:
if vowel [0]=='a,e':
words.append(vowel)
print (words)
我的代碼不正確,它會打印出原始列表中的所有單詞。如何用Python找出列表中以元音開頭的單詞?
words = ['apple', 'orange', 'pear', 'milk', 'otter', 'snake','iguana','tiger','eagle']
for word in words:
if word[0] in 'aeiou':
print(word)
您也可以使用列表理解這樣
words_starting_with_vowel = [word for word in words if word[0] in 'aeiou']
if vowel [0]=='a,e':
words.append(vowel)
你在這裏追加到原始列表。它應該是您的vowel
列表。
words = ['apple', 'orange', 'pear', 'milk', 'otter', 'snake','iguana','tiger','eagle']
vowel=[]
for word in words:
if word[0] in "aeiou":
vowel.append(word)
print (vowel)
使用列表理解
vowel = [word for word in words if word[0] in "aeiou"]
使用filter
vowel = filter(lambda x : x[0] in "aeiou",words)
對不起,我不小心投了票。你幫了很多忙。謝謝。 – user1718826
這裏是一個班輪答案與列表理解:
>>> print [w for w in words if w[0] in 'aeiou']
['apple', 'orange', 'otter', 'iguana', 'eagle']
+1用於列表理解 – ahans
好蟒蛇讀起來幾乎像NATU拉爾語言:
vowel = 'a', 'e', 'i', 'o', 'u'
words = 'apple', 'orange', 'pear', 'milk', 'otter', 'snake', 'iguana', 'tiger', 'eagle'
print [w for w in words if w.startswith(vowel)]
與w[0]
解決方案的問題是,它並沒有空話工作(沒有在這個特殊的例子沒關係,但像解析用戶輸入在現實生活中很重要的任務)。
元音應該是「aeiou」 – user1718826
問題:1.用循環變量覆蓋'元音'。 2.將'元音'附加到循環的列表中。 – 2012-10-11 06:34:21
'元音[0] =='a,e''永遠不會是真的。您正在比較一個字符串與三個字符的字符串。你想要'ae''中的元音[0]。 – asmeurer