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

2024-05-17 17:00:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我有五根弦。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

Tags: orthe方法代码fromifrc1are
3条回答

您的问题与标题不一致(“正好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))

这是字典的经典用例:

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))

由于列表的大小为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")

相关问题 更多 >