Python 如何修复我的代码及其价格<;生成器对象<;genexpr>;在…>;?

Python 如何修复我的代码及其价格<;生成器对象<;genexpr>;在…>;?,python,Python,我得到一个错误,我不知道为什么我的函数返回生成器对象,我如何修复它 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:

我得到一个错误,我不知道为什么我的函数返回
生成器对象
,我如何修复它

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})
测试“compute\u word\u importance()”是否为空文件返回空计数器。
好:返回的计数器是正确的。
测试“compute_word_importance()”是否为空的第一个文件返回带负值的计数器。
错误:返回的计数器不正确:
... 观察:计数器({:-1,:-1,:-1,:-1,:-1,:-1})
... 应为:计数器({'yybieqgmuhqaqrkrfjtjoegqgxgza':-1,'lbcqhmlnpvz':-1,'igr':-1,'kzjry':-1,'tuas':-1,'f':-1,'twmu':-1,'zvg':-1,'j':-1,'vqdkprzqc':-1})

例如。预期输出
计数器({'language':1,'Python':1,'programming':1,'about':0,'is':0,'text':0,'Spam':-1})
如果您想要一个基于您正在计算的事实的元素的平面列表,那么它正是您想要的,extend还将使用生成器表达式:

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

如果要将列表附加到
tmp\u列表中,那么您将尝试将列表列表传递给计数器,但该计数器不起作用。

tmp\u list.append(word.strip()表示行中的word.split())
。您正在将生成器附加到列表中。是否希望每一行都成为自己的列表?还是所有的都应该是一个列表?所有的都在一个列表中,就像我刚才编辑我的post@loco如果这个答案,请考虑点击在左边的检查标记/滴答,把它变成绿色。这标志着问题已解决,令您满意,并奖励您和回答者。