我正在尝试测量列表的冗余率。
让我们假设:
L = [a, a, a, a] => redundancy rate = 1
L = [a, b, c, d] => redundancy rate = 0
L = [a, a, b, b] => redundancy rate = 0.5我不能以一种有意义的方式来结束。
发布于 2020-12-28 02:56:19
尽管输出与问题描述中的值匹配,但我不太确定这是否是有效的度量。也许min比mean更好。
import pandas as pd
l1 = ['a', 'a', 'a', 'a']
l2= ['a', 'b', 'c', 'd']
l3 = ['a', 'a', 'b', 'b']
def f(l):
s = pd.Series(l)
ratio = s.value_counts() / len(l)
redundantContent = s[s.duplicated(keep='first')]
if not redundantContent.empty:
return redundantContent.map(ratio).mean()
else:
return 0
print("redundancy rate of l1: {}".format(f(l1)))
print("redundancy rate of l2: {}".format(f(l2)))
print("redundancy rate of l3: {}".format(f(l3)))输出
redundancy rate of l1: 1.0
redundancy rate of l2: 0
redundancy rate of l3: 0.5发布于 2020-12-28 01:20:30
将冗余定义为1 - num_unique_elements / num_total_elements。我假设您的意思是重复列表的冗余度永远不会恰好为1。例如:
lsts = [[1, 1, 1, 1], [1, 1, 2, 2], [1, 2, 3, 4]]
for lst in lsts:
redundancy = 1 - len(set(lst)) / len(lst)
print(redundancy)
# 0.75
# 0.5
# 0.0发布于 2020-12-28 01:20:37
多亏了Timur Shtatland的评论,我已经提出了一个与给定概念相匹配的程序,并对其进行了优化。我要提到的一件事是,它为你的第一个测试用例提供了0.75冗余,这是因为只有75%的列表是冗余的,这似乎就是你想要的(但如果不是,请告诉我)。
unique = []
for item in L:
if item not in unique:
unique.append(item)
redundancy = 1 - len(unique) / len(L)编辑:正如在Timur的回答中所看到的,使用set来定义unique而不是编写for循环会更简洁。
https://stackoverflow.com/questions/65468253
复制相似问题