Python 比较4个数字,找出3个是否相同

Python 比较4个数字,找出3个是否相同,python,list,Python,List,我有以下Python列表: mylist = [a, b, c, d] 其中a、b、c、d是整数 我想比较一下4的数字,看看它们的3是否相同 我已尝试将列表转换为集合,但没有帮助。您可以尝试以下操作: if mylist.count(mylist[0])>=3 or mylist.count(mylist[1])>=3: print('3 are the same') mylist = [a, b, c, d] counter = {a:mylist.count(a) f

我有以下Python
列表

mylist = [a, b, c, d]
其中
a、b、c、d
整数

我想比较一下
4
的数字,看看它们的
3
是否相同

我已尝试将
列表
转换为
集合
,但没有帮助。

您可以尝试以下操作:

if mylist.count(mylist[0])>=3 or mylist.count(mylist[1])>=3:
    print('3 are the same')
mylist = [a, b, c, d]
counter = {a:mylist.count(a) for a in mylist}
if 1 in counter.values() and len(counter) == 2:
   print("three are the same")

尝试
集合。计数器

import collections

x = [1, 2, 1, 1]
counter = collections.Counter(x)
if 3 in counter.values():
    print('3 are the same')
输出:

3 are the same
更新

如果您有兴趣检查3次或3次以上的情况,可以在
计数器中检查最大值,如下所示:

if max(counter.values()) >= 3:
    print('3 or more are the same')
这种方法还有一个额外的优点,即它可以在不修改的情况下适用于较大的列表。

这里有一种方法:

mylist = [a, b, c, d]
d = {}

for i in mylist:
   d[i] = d.get(i, 0) + 1 

if 3 in d.values():
   print("three are the same")

您可以使用
集合计数器

from collections import Counter
same3 = Counter(mylist).most_common(1)[0][1] >= 3
如果至少有3个元素相同,则为真。

此解决方案使用


我建议使用
collections.Counter

import collections

x = [1, 2, 1, 1]
counter = collections.Counter(x)
if 3 in counter.values():
    print('3 are the same')
将列表转换为计数器。计数器应有两个键,其中一个值应为3:

In [1]: from collections import Counter

In [2]: c = Counter([0, 1, 1, 1])

In [3]: len(c) == 2
Out[3]: True

In [4]: 3 in c.values()
Out[4]: True
简言之:

In [5]: len(c) == 2 and 3 in c.values()
Out[5]: True
让我们尝试一个不符合标准的示例:

In [8]: d = Counter([0, 0, 1, 1])

In [9]: len(d) == 2 and 3 in d.values()
Out[9]: False

检查最高计数

max(map(mylist.count, mylist)) >= 3

你能给我们看一下你现在的代码吗?你得到的结果是什么?三个数字是一样的吗?@切普纳:考虑<代码>(0, 0, 1,1)< /代码> @ Robᵩ LOL我们有完全相同的想法:PBy“相同”,你的意思是相等还是相同?谢谢,这非常有效,而且是迄今为止最容易实现的,无需导入额外的模块。@user3913519所以对于
[1,1,1,1]
你想要
False
,即使其中三个是相同的?@Robᵩ 哈哈,不过我真的不确定。大多数回答者显然将其解释为“==3”,也许OP的意思是这样的。应该在问题中说得更清楚。@StefanPochmann我的主要if语句是针对4个相同的数字。所以罗布的建议对我来说非常好