不,这不仅仅是使用 count() 这么简单
我有一个 5 个随机整数的列表,从 0 到 9。我想检查这些整数中的 3 个是否相同,以及其余 2 个是否相同但与其他 3 个不同。
我的想法是使用 set() 来计算列表中出现的次数,但这也包括有 4 个相同整数和 1 个单独整数的情况,如下所示:
nums = [4, 4, 4, 2, 2]
if len(set(nums)) == 2:
print(set(nums))
>> {4, 2}
nums = [4, 4, 4, 4, 2]
if len(set(nums)) == 2:
print(set(nums))
>> {4, 2}
我一直在努力寻找一种方法来排除 4x1 的情况,但我想出的一切似乎都令人费解,而且像是糟糕的做法,这需要干净利落。我想知道是否有更好的方法可以在不使用 set() 的情况下执行此操作?
感谢您的帮助。
请您参考如下方法:
您可以使用以数字作为键、以值作为频率的字典
from collections import Counter
nums = [4, 4, 4, 2, 2]
freq_dict = dict(Counter(nums))
print(freq_dict)
会给你这个:
{4: 3, 2: 2}
然后我们可以检查字典的长度是否为 2 的条件,否则意味着它有超过 2 个相同的元素。
if len(freq_dict) == 2:
for key, value in freq_dict.items():
if value == 2 or value == 3:
print("Given that there are 5 items and the length of the list is 2, it has to be the case that \
the other integer appears {} times".format(5 - value))
print(key)
break
else:
print("Nope")
