Python 有没有办法检查5个字符串中的4个是否相等?
我有五根弦。4个是相同的,假设它们都是Python 有没有办法检查5个字符串中的4个是否相等?,python,python-3.x,Python,Python 3.x,我有五根弦。4个是相同的,假设它们都是'K',另一个是不同的,'J'。是否有一种方法可以比较所有这些数据,并检查五分之四是否正好相等 伪代码: 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”或“至少4”?),但如果不是所有问题都相同,则会打印错误: if len(set(
'K'
,另一个是不同的,'J'
。是否有一种方法可以比较所有这些数据,并检查五分之四是否正好相等
伪代码:
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”或“至少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))
由于列表大小为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")
这是字典的经典用例:
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))
使用groupby获得字符串的出现次数。我认为这种方法更一般。这不是最有效的方法,但它很简洁。
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')