Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/9.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,我是python的初学者,对编码还不太了解。 这是我在维基百科上得到的: 你是说这个吗 count = 0 for i in list: if i == string: count += 1.0 return count / len(list) 这是错误的。你是说这个吗 count = 0 for i in list: if i == string: count += 1.0 return count / len(list) len(filter(

我是python的初学者,对编码还不太了解。
这是我在维基百科上得到的:

你是说这个吗

count = 0
for i in list:
    if i == string:
       count += 1.0
return count / len(list)
这是错误的。

你是说这个吗

count = 0
for i in list:
    if i == string:
       count += 1.0
return count / len(list)
len(filter(lambda x: x == 'apple', list1)) / float(len(list1))

sum(map(lambda x: x == 'apple', list1)) / float(len(list1))

reduce(lambda x, y: x + (y == 'apple'), list1, 0.0) / len(list1)

这是错误的。

您可以使用
集合。计数器

len(filter(lambda x: x == 'apple', list1)) / float(len(list1))

sum(map(lambda x: x == 'apple', list1)) / float(len(list1))

reduce(lambda x, y: x + (y == 'apple'), list1, 0.0) / len(list1)
>>> from collections import Counter
>>> c1 = Counter(list1)
>>> c2 = Counter(list2)
>>> def rec_rank(key,dic):
...     return dic[key]/float(sum(dic.values()))
... 
>>> rec_rank('apple',c1)
0.3333333333333333
>>> rec_rank('apple',c2)
0.5

您可以使用集合。计数器:

>>> from collections import Counter
>>> c1 = Counter(list1)
>>> c2 = Counter(list2)
>>> def rec_rank(key,dic):
...     return dic[key]/float(sum(dic.values()))
... 
>>> rec_rank('apple',c1)
0.3333333333333333
>>> rec_rank('apple',c2)
0.5

什么是查询,什么是响应?什么是平均倒数排名?你尝试了什么?什么是查询,什么是回应?什么是平均倒数排名?你试过什么?不,我是指一个可以计算倒数排名的函数,比如对于第一个链接,如果我键入函数->水果('apple'),结果将是list1的1/3,因为它在列表中只出现过一次。但对于第二个列表,结果将是1/2,因为它在一个列表中出现两次list@Erika我在维基百科上查到了。它不取决于序列中正确项目的数量。啊,是的!我的坏:(这也取决于排名。)不,我指的是一个可以计算倒数排名的函数,例如,如果我键入函数->水果('apple'),第一个链接的倒数排名,列表1的结果将是1/3,因为它在列表中只出现过一次。但对于第二个列表,结果将是1/2,因为它在一个列表中出现过两次list@Erika我在维基百科上查过。它不取决于序列中正确项目的数量。啊,是的!我的错:(它也取决于排名。)。。