gpt4 book ai didi

python - 如何确定任何值是否在列表中出现两次以上?

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:08:40 24 4
gpt4 key购买 nike

我有一个列表,想确定是否有任何值出现超过两次。我试过使用集合和计数器,但我无法让它们评估为单个 True 或 False 值。

myArray=[1,1,1,1,1,1,1,1,2]

我希望它返回:True 如果任何 值出现超过两次

感谢任何帮助,如果解决方案很快,那将非常有帮助。我正在检查数十万个列表。我是编程新手,这是我的第一篇文章。

编辑:我的尝试,我也是 stackoverflow UI 的新手

导入集合

arr= [1,2,3,5,6]

计数器(arr)

返回:Counter({1: 1, 2: 1, 3: 1, 5: 1, 6: 1})

最佳答案

您可以使用 collections.Counter为此:

from collections import Counter
print any(count > 2 for count in Counter(myArray).itervalues()) # True

或者,如果您使用的是 Python 3:

from collections import Counter
print(any(count > 2 for count in Counter(myArray).values())) # True

关于python - 如何确定任何值是否在列表中出现两次以上?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51198845/

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