如何在 python 中查找元组的重复项

How to find the repeated items of a tuple in python

tup=(1,3,4,32,1,1,1)  
for i in tup:
    if tup.count(i) > 1:
        print('REPEATED')

Image of what i tried

您可以使用 collections.Counter:

from collections import Counter

for k, v in Counter(tup).items():
    if v > 1:
        print("Repeated: {}".format(k))
tup=(1,3,4,32,1,1,1,31,32,12,21,2,3)  
for i in tup:
    if tup.count(i) > 1:
        print(i)
var=int(input())
tup=(10, 8, 5, 2, 10, 15, 10, 8, 5, 8, 8, 2)  
a=list(tup)
for i in range(len(a)):
  a[i]=int(a[i])
count=a.count(var)
print(var,'appears',count,'times in the tuple')

示例输入

8

示例输出

8 在元组中出现了 4 次

执行此操作的 Pythonic 方法是使用 collections.Counter:

>>> from collections import Counter
>>> t = (1,1,1,1,1,2,2,2,3,3,4,5,6,7,8,9)
>>> c = Counter(t)
>>> c
Counter({1: 5, 2: 3, 3: 2, 4: 1, 5: 1, 6: 1, 7: 1, 8: 1, 9: 1})

计数器 returns 可以迭代的 dict-like 对象,以及其他操作。