簡體   English   中英

Python - 如果源是文件,則求和在列表理解語法中不起作用

[英]Python - Sum not working in list comprehension syntax if the source is file

我是Python的新手,正在學習列表理解。

我要做的是將以下代碼轉換為列表推導式:

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

這是我微弱的嘗試:

words = open('words.txt')
print sum([1 for word in words if word.find('e') == -1])

但不幸的是它不起作用。 我希望得到的答案是 37641,但我得到的是 0。:(

我嘗試創建另一個代碼來做同樣的事情,但我沒有使用文件作為源,而是使用了一個列表:

def test():
    words = ['hello', 'world', 'ciao']
    return sum([1 for word in words if word.find('e') == -1])

它有效。

我看到了這個“非常”相似的 SO 帖子並嘗試了那里發布的代碼return len([word for word in words if len(word) >= 2 and word[0] == word[-1]]) 如果源是硬編碼列表,它可以工作,但如果源是外部文件,它就會失敗。

現在,我的問題是, sum只適用於列表和元組嗎? 如果我正確理解文檔,則可以總結任何可迭代對象。

任何啟示將不勝感激。 :)

最簡單的解決方案是:

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

如您所見, sum確實適用於任何迭代器 - 此處我使用的是生成器表達式。

而不是做word.find('e') == -1我們可以只做"e" not in word這樣更好讀並且可以工作,因為字符串本身是可迭代的並且支持__contains__

我還使用with語句打開文件——這比手動打開和關閉文件更可取,因為它會為您處理這些事情,並且還能正確處理異常。

但是我想指出,您的示例對我有用。 我的猜測是您的文件是用空格或逗號分隔的,但是遍歷文件會返回行。

我的測試文件:

bob
bill
james
test
something
no

例如,這將不起作用:

bob bill james test something no

因為我們將得到一個包含整個東西的字符串。 在這種情況下,我們可以使用str.split()將行拆分為單詞。

例如:

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

我剛剛嘗試過這個,並且有效,所以它可能與您的文件格式有關:

me@pc:~/Desktop$ cat > words.txt
app
noot
mies
wim
zus
jet
me@ps:~/Desktop$ python
Python 2.6.6 (r266:84292, Dec 26 2010, 22:31:48) 
[GCC 4.4.5] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> sum(1 for word in open('words.txt') if 'e' not in word)
4

好的。 我嘗試了@Lattyware 編寫的代碼,它工作正常。 我想我已經找到了罪魁禍首,盡管我不明白為什么它會那樣做。 我想那將是另一個問題。 :)

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


>>> count_words()
113809
0

但是當我注釋掉第一個打印語句時,它正確地顯示了答案。

>>> count_words()
37641

更新:

我發布了我想出的解決方案,以防其他人遇到同樣的問題。

def count_words():
    total = 0
    wordsWithoutE = 0

    with open("words.txt") as words:
        for word in words:
            if 'e' not in word:
                wordsWithoutE += 1

            total += 1

    return (total, wordsWithoutE)


    >>> print count_words()
    (113809, 37641)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM