Reputation: 27
Newbie to Python...trying to take sentence = "Anyone who has never made a mistake has never tried" and:
Able to convert sentence to list using 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']
Need help with the list comprehension. No clue where to start.
Upvotes: 1
Views: 87
Reputation:
Python syntax helps usually to understand what the code does. Hope you get the idea how to filter items from a list using a given if
condition:
# 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 )
gives:
['has', 'made', 'a', 'mistake', 'has', 'anything']
Upvotes: 1
Reputation: 17532
You have a list of word and you want to get the words that start with 'A', 'H', or 'M'. So, check that condition in the list comprehension:
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']
Your result is in ahm_words
.
See: https://docs.python.org/2/tutorial/datastructures.html#list-comprehensions.
Upvotes: 1