Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/353.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/database/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
用python枚举_Python - Fatal编程技术网

用python枚举

用python枚举,python,Python,说 term='asdf';inversedindex={};逆变器索引[术语]=[1,2,2,4,5,6,6,6,6,7] 现在我们有了这个函数,它计算任何项目的发生次数。这是我遇到问题的函数 def TF(term, doc): idx = InvertedIndex[term].index(doc) return next(i for i, item in enumerate(InvertedIndex[term][idx:]) if it

term='asdf';inversedindex={};逆变器索引[术语]=[1,2,2,4,5,6,6,6,6,7]

现在我们有了这个函数,它计算任何项目的发生次数。这是我遇到问题的函数

def TF(term, doc):
    idx = InvertedIndex[term].index(doc)
    return next(i  for i, item in enumerate(InvertedIndex[term][idx:])
                if item != doc)
它给出1表示
TF(术语,1)
,3表示
TF(术语,2)
,1表示
TF(术语,4)
。到目前为止还不错

但是对于
TF(term,7)
,它给出了StopIteration错误。如果我使用
InvertedIndex[term]=[7]
并调用
TF(term,7)
,它也会给出相同的错误。如何修复它

编辑: 澄清功能的目的。该函数用于计算项目发生的次数。考虑到所使用的示例TF(term,2)必须返回3,因为它在InvertedIndex[term]中出现了3次

解决方案:

def TF(term, doc):
    return InvertedIndex[term].count(doc)

在语言级别,您的问题是您正在对序列调用“next”,当序列为空时,它将引发StopIteration

否则,不清楚如何帮助您,因为您编写的函数应该做什么并不明显。您可能需要以下内容:

def uniq_docs(inverted_index):
    last = None
    for i, doc in enumerate(inverted_index):
        if doc != last:
            yield i, doc
            last = doc
在您当前呼叫TF的地方,请使用以下命令:

for index, doc in uniq_docs(InvertedIndex[term]):
    ...

我觉得我在另一个答案上写了这个循环,但正确的答案是
invertdindex[term].count(doc)


这将计算列表中出现
doc
的次数。

我认为如果您使用python>=2.7并且想要计算每个项,那么应该使用.Counter。很抱歉,没有明确函数的目标。该函数用于计算项目发生的次数。考虑到所使用的示例
TF(term,2)
必须返回3,因为它在InvertedIndex[term]中出现了3次该死!我不知道有一个count()方法。还有一个小小的修正,它的
InvertedIndex[term].count(doc)
这就是为什么我应该在开始为项目编码之前花足够的时间学习该语言的原因。@claws,我确实编写了该函数。对不起,里面有个愚蠢的虫子。每当我试图写一些甚至有点棘手的东西而不进行测试时,它就会发生(尽管我正在变得更好)。显然,我在第一次编写时也没有考虑
count
方法。我已经更新了对原始问题的答案。