Python列表理解方法

时间:2017-04-21 00:25:33

标签: python list-comprehension

新手到Python ......试图接受判决="任何从未犯过错误的人从未尝试过#34;和

  1. 将句子转换为列表
  2. 使用列表理解创建一个新列表,其中包含以字母开头的单词' A,H和M'。
  3. 能够使用 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']
    

    需要列表理解方面的帮助。不知道从哪里开始。

2 个答案:

答案 0 :(得分:1)

你有一个单词列表,你想得到以'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

答案 1 :(得分:1)

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']