新手到Python ......试图接受判决="任何从未犯过错误的人从未尝试过#34;和
能够使用 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']
需要列表理解方面的帮助。不知道从哪里开始。
答案 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']