gpt4 book ai didi

python - 计算列表中的项目出现次数 - python 方式

转载 作者:行者123 更新时间:2023-11-28 22:49:35 26 4
gpt4 key购买 nike

我的代码:

result = 0
for line_A in text_A:
for line_B in text_B:
if line_A in line_B:
result += 1
break
return result / len(text_A)

非常简单:如果 text_A 中的 line_A 存在于 text_B 中,计算它并检查另一个。我想知道我是否遗漏了一些实用工具,或者这种方法是否 100% 正确?蒂亚

最佳答案

您可以将两个文本都转换为集合并取交集,就像这样

len(set(text_A) & set(text_B)) / len(text_A)

但这里的问题是,如果有重复的文本,那么它只会被计算一次。所以,你可能想使用

sum(line_A in text_B for line_A in text_A) / len(text_A)

但是如果 line_A 可以在 line_B 的任何地方,那么你所拥有的就是正确的,可以像这样简洁地写出来

sum(any(line_A in line_B for line_B in text_B) for line_A in text_A)/len(text_A)

关于python - 计算列表中的项目出现次数 - python 方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23690880/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com