[英]Python List Comprehension how-to
Python的新手...試圖接受句子=“從未犯過錯誤的人從未嘗試過”並且:
能夠使用string.split()將句子轉換為列表
string = "Anyone who has never made a mistake has never tried anything new"
string.split()
['Anyone', 'who', 'has', 'never', 'made', 'a', 'mistake', 'has', 'never', 'tried', 'anything', 'new']
在列表理解方面需要幫助。 不知道從哪里開始。
您有一個單詞列表,並且想要獲取以“ A”,“ H”或“ M”開頭的單詞。 因此,請檢查列表理解中的條件:
string = "Anyone who has never made a mistake has never tried anything new"
words = string.split()
ahm_words = [w for w in words if w.lower()[0] in 'ahm']
您的結果在ahm_words
。
請參閱: https : //docs.python.org/2/tutorial/datastructures.html#list-comprehensions 。
Python語法通常有助於理解代碼的作用。 希望您能了解如何使用給定的if
條件從列表中過濾項目:
# string = "Anyone who has never made a mistake has never tried anything new"
# string.split()
listOfWords = ['Anyone', 'who', 'has', 'never', 'made', 'a', 'mistake', 'has', 'never', 'tried', 'anything', 'new']
listOfChars = ['a', 'h', 'm']
wordsBeginningWithAHM = [word for word in listOfWords if word[0] in listOfChars]
print( wordsBeginningWithAHM )
給出:
['has', 'made', 'a', 'mistake', 'has', 'anything']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.