簡體   English   中英

Python列表理解方法

[英]Python List Comprehension how-to

Python的新手...試圖接受句子=“從未犯過錯誤的人從未嘗試過”並且:

  1. 將句子轉換為列表
  2. 使用列表推導創建一個包含以字母“ A,H和M”開頭的單詞的新列表。

能夠使用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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM