Python-如果源是文件,Sum不能使用列表推导语法 [英] Python - Sum not working in list comprehension syntax if the source is file

查看:42
本文介绍了Python-如果源是文件,Sum不能使用列表推导语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Python的新手,正在研究列表理解.

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

但不幸的是,它无法正常工作.我希望得到的答案是37641,但是我得到的是0.:(

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

它有效.

我看到了类似的相当"这样的 post 并尝试了其中发布的代码返回len([如果len(word)> = 2且word [0] == word [-1]],则逐字逐字地输入).如果源是硬编码列表,则该方法有效,但如果源是外部文件,则该方法将失败.

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.

现在,我的问题是, sum 仅适用于列表和元组吗?如果我理解

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. :)

推荐答案

最简单的解决方案是:

with open("words.txt") as words:
  sum(1 for word in words if "e" not in word)

如您所见, sum 可以与任何迭代器一起使用-这里我使用的是生成器表达式.

As you can see, sum does work with any iterator - here I am using a generator expression.

我们不用做 word.find('e')== -1 ,而只需做"e"而不是单词,这样更易​​于阅读,并且可以字符串本身是可迭代的,并且支持 __ contains __ .

Rather than doing word.find('e') == -1 we can just do "e" not in word which is nicer to read and works as strings are iterable themselves and support __contains__.

我还使用 with 语句打开文件-这比手动打开和关闭文件更可取,因为它可以为您处理这些事情,并且也可以正确处理异常.

I am also using the with statement 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.

我的测试文件:

bob
bill
james
test
something
no

例如,这将不起作用:

bob bill james test something no

因为我们将得到一个包含整个内容的字符串.在这种情况下,我们可以使用 str.split()将行拆分为单词.

As we will get one string containing the whole thing. In this case, we can use str.split() to split the lines into words.

例如:

with open("words.txt") as lines:
    sum(1 for line in lines for word in line.split() if "e" not in word)

这篇关于Python-如果源是文件,Sum不能使用列表推导语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆