有没有办法检查5个字符串中的4个字符串是否相等?

时间:2019-10-10 02:49:53

标签: python python-3.x

我有5个字符串。 4个相同,可以说它们都是'K',而另一个是'J'。有没有办法比较所有这些,并检查5个中的4个是否相等。

伪代码:

rc1 = 'K'
rc2 = 'J'
rc3 = 'K'
rc4 = 'K'
rc5 = 'K'

if four are the same from rc1, rc2, rc3, rc4 or rc5:
    print error

4 个答案:

答案 0 :(得分:2)

您的问题与您的标题不符(“正好是4” “至少4” ?),但是如果并非全部都这样,则会打印错误一样:

if len(set([rc1, rc2, rc3, rc4, rc5])) > 1:
    print("Error")

更新:如果您需要检查它们中的 n 是否完全相同,则可以执行以下操作:

items = [rc1, rc2, rc3, rc4, rc5]
n = 4
if any(items.count(item) == n for item in items):
    print("{} of them are the same, {} is different".format(n, len(items) - n))

或者您实际上可以计算出最重复的元素:

max_repeat = max(items.count(item) for item in items)
print("{} of them are the same".format(max_repeat))

答案 1 :(得分:1)

由于列表的大小为5,这等效于检查列表中的第一项或第二项是否恰好出现了4次。您可以使用两次list.count来做到这一点:

def AreFourItemsEqual(l):
    return l.count(l[0]) == 4 or l.count(l[1]) == 4

if AreFourItemsEqual([rc1,rc2,rc3,rc4,rc5]):
    print ("Error")

答案 2 :(得分:0)

这是字典的经典用例:

rc1 = 'K'
rc2 = 'J'
rc3 = 'K'
rc4 = 'K'
rc5 = 'K'
strs = [rc1, rc2, rc3, rc4, rc5]

def four_out_of_five_match(strs):
    d = {}
    for str in strs:
        d[str] = d.get(str, 0) + 1
        if d[str] == 4:
            return True
    return False

print(four_out_of_five_match(strs))

答案 3 :(得分:-2)

from itertools import groupby

strs = [rc1, rc2, rc3, rc4, rc5]
count = [len(list(group)) for key, group in groupby(strs)]
if 4 in count or 5 in count:
    print('error')

使用groupby获得字符串出现的次数。我认为这种方法更通用。

相关问题