怎么能修复我的代码它的引用<generator object =“”<genexpr =“”> at ...&gt;?

时间:2015-12-10 21:30:40

标签: python

我收到错误,我不知道为什么我的函数返回generator object <genexpr>,我该如何解决?

import collections

def compute_word_importance(fpath1,fpath2):
    lists = []
    for filepath in (fpath1, fpath2):
        tmp_list = []
        with open(filepath, 'rt', encoding='UTF-8') as inputfile:
            for line in inputfile:
                tmp_list.append(word.strip() for word in line.split())

            lists.append(tmp_list)

    if lists[0] == lists[1] == 0:
         return None

    counter = collections.Counter(lists[0])
    counter.subtract(lists[1])
    return counter

自动评估

Testing if "compute_word_importance()" returns an empty Counter for empty files.
OK: The returned Counter is correct.
Testing if "compute_word_importance()" returns Counter with negative values for empty first file.
ERROR: The returned Counter is not correct:
... Observed: Counter({<generator object <genexpr> at 0x7f13de3b6708>: -1, <generator object <genexpr> at 0x7f13de3b6630>: -1, <generator object <genexpr> at 0x7f13de3b66c0>: -1, <generator object <genexpr> at 0x7f13de3b6750>: -1, <generator object <genexpr> at 0x7f13de3b6678>: -1})
... Expected: Counter({'yybieqgmuhqaqrkrfjtjoegqgxgza': -1, 'lbcqhmlnpvz': -1, 'igr': -1, 'kzjry': -1, 'tuas': -1, 'f': -1, 'twmu': -1, 'zvg': -1, 'l': -1, 'j': -1, 'vqdkprzqc': -1})

例子。预期产出Counter({'language.': 1, 'Python': 1, 'programming': 1, 'about': 0, 'This': 0, 'is': 0, 'text': 0, 'Spam.': -1})

1 个答案:

答案 0 :(得分:1)

如果你想要一个基于你正在计算的事实的元素的平面列表,你希望extend 不是 append,扩展也可以使用生成器表达式:

tmp_list.extend(word.strip() for word in line.split())

如果您要将列表附加到tmp_list,那么您将尝试将列表列表传递给计数器,这将无效。