I’m a newbie in Python and I’m studying list comprehension.
What I’m trying to do is to convert the following code into list comprehension:
def words_without_e():
count = 0
words = open('words.txt')
for word in words:
if word.find('e') == -1:
count += 1
words.close()
return count
Here’s my feeble attempt:
words = open('words.txt')
print sum([1 for word in words if word.find('e') == -1])
But unfortunately it’s not working. The answer I expect to get is 37641, but I’m getting 0. 🙁
I tried creating another code doing the same thing but instead of file as source, I used a list:
def test():
words = ['hello', 'world', 'ciao']
return sum([1 for word in words if word.find('e') == -1])
And it works.
I saw this “quite” similar SO post and tried the code posted there return len([word for word in words if len(word) >= 2 and word[0] == word[-1]]). It works if the source is a hard-coded list but fails if the source is an external file.
Now, my question is, does sum only works with lists and tuples? If I understood the docs correctly, any iterable could be summed up.
Any enlightenment would be very much appreciated. 🙂
The simplest solution is this:
As you can see,
sumdoes work with any iterator – here I am using a generator expression.Rather than doing
word.find('e') == -1we can just do"e" not in wordwhich is nicer to read and works as strings are iterable themselves and support__contains__.I am also using the
withstatement to open files – this is preferable to manually opening and closing them as it handles those things for you, and handles exceptions correctly too.I would like to note however, your example works for me. My guess is that your file is space or comma delimited, but looping through a file returns lines.
My test file:
This, for example, will not work:
As we will get one string containing the whole thing. In this case, we can use
str.split()to split the lines into words.E.g: