首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python:计算列表的冗余率

Python:计算列表的冗余率
EN

Stack Overflow用户
提问于 2020-12-28 01:06:25
回答 3查看 75关注 0票数 1

我正在尝试测量列表的冗余率。

让我们假设:

代码语言:javascript
复制
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

我不能以一种有意义的方式来结束。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2020-12-28 02:56:19

尽管输出与问题描述中的值匹配,但我不太确定这是否是有效的度量。也许minmean更好。

代码语言:javascript
复制
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)))

输出

代码语言:javascript
复制
redundancy rate of l1: 1.0
redundancy rate of l2: 0
redundancy rate of l3: 0.5
票数 1
EN

Stack Overflow用户

发布于 2020-12-28 01:20:30

将冗余定义为1 - num_unique_elements / num_total_elements。我假设您的意思是重复列表的冗余度永远不会恰好为1。例如:

代码语言:javascript
复制
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
票数 2
EN

Stack Overflow用户

发布于 2020-12-28 01:20:37

多亏了Timur Shtatland的评论,我已经提出了一个与给定概念相匹配的程序,并对其进行了优化。我要提到的一件事是,它为你的第一个测试用例提供了0.75冗余,这是因为只有75%的列表是冗余的,这似乎就是你想要的(但如果不是,请告诉我)。

代码语言:javascript
复制
unique = []

for item in L:
    if item not in unique:
        unique.append(item)

redundancy = 1 - len(unique) / len(L)

编辑:正如在Timur的回答中所看到的,使用set来定义unique而不是编写for循环会更简洁。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65468253

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档