Reputation: 2508
I am trying to use list comprehension in order to extract only words which have characters which is greater then 3. I already made this line of code which count that words.
ListWord = [len(x.strip(',')) for x in 'Michael Jordan is the best basketball player of all time'.split() if len(x.strip(','))>3]
ListWord
Out[73]: [7, 6, 4, 10, 6, 4]
But now I need to see that words not only to count е.g["Michael","Jordan","best","basketball","player","time"].
So can anybody help me how to solve this problem ?
Upvotes: 0
Views: 568
Reputation: 28565
Why are you using strip? Simpler to just .split()
(that returns a list of each item) of the string, and then check the length of each item in that list:
list_word = [x for x in 'Michael Jordan is the best basketball player of all time'.split() if len(x)>3]
Output:
print(list_word)
['Michael', 'Jordan', 'best', 'basketball', 'player', 'time']
Upvotes: 1
Reputation: 1581
Let's take a look at your query.
[len(x.strip(',')) for x in 'Michael Jordan is the best basketball player of all time'.split() if len(x.strip(','))>3]
If we break this into components, it will be
[TO_RETURN for CURRENT_ITEM in LIST if CONDITION]
So, if you would like to return something different, replace TO_RETURN
. In this case, x.strip(',')
instead of len(x.strip(','))
.
Upvotes: 1
Reputation: 1455
Replace len(x.strip(',')) with x.strip(',')
ListWord = [x.strip(',') for x in 'Michael Jordan is the best basketball player of all time'.split() if len(x.strip(','))>3]
print(ListWord)
Upvotes: 1