Count the number of duplicate tuples inside a list

Viewed 99

I want to count the number of duplicated tuples in a list.

For example num_list:

num_list = [(3,14),(2,8),(10,25),(5,17),(3,2),(7,25),(4,30),(8,7),(int(2),8),(1,22)]

I want to return the result: Total duplicates: 1 which is the (2, 8) pair.

what i have so far is not very efficient, so I am wondering if there's a more efficient way to do this?

count = 0
for a in num_list:
  for b in num_list:

     if a is b:
         continue

     if a[0] == b[0] and a[1] == b[1]:
         count += 1
4 Answers
num_list = [(3,14),(2,8),(10,25),(5,17),(3,2),(7,25),(4,30),(8,7),(int(2),8),(1,22)]

dupe_count = len(num_list) - len(set(num_list))

print(dupe_count)

If you cared about the actual items appearing more than once, the most efficient way is to use Counter:

from collections import Counter

c = Counter(num_list)

c = {k: v for k, v in c.items() if v > 1}

print(c)

Gives a dict of items appearing more than once and their frequency:

{(2, 8): 2}
num_list = [(3, 14), (2, 8), (10, 25), (5, 17), (3, 2), (7, 25), (4, 30), (8, 7), (2, 8), (1, 22)]
mostappear = ()
appeartime = 0
for n in num_list:

    count = num_list.count(n)
    if count > appeartime:
        print(count)
        appeartime = count
        mostappear = n
print(appeartime,mostappear)

You can use a set for look-up:

lookup = set()
dupes = []

for i in lst:
    if i in lookup:
        dupes.append(i)
    else:
        lookup.add(i)

print(dupes)
# [(2, 8)]
print(len(dupes))
# 1

Swift

Giving this swift version:

let numList = [(3,14),(2,8),(10,25),(5,17),(3,2),(7,25),(4,30),(8,7),(Int(2),8),(1,22)]

You can convert items to something Hashable to detect duplicate:

struct HashablePair: Hashable {
    init(_ pair: (AnyHashable, AnyHashable)) { (a, b) = pair }
    let (a, b): (AnyHashable, AnyHashable)
}

And then do the subtraction to count the difference:

let count = numList.count - Set(numList.map { HashablePair($0) } ).count
print(count)

If you cared about the actual items appearing more than once, you can use Dictionary:

let counted = Dictionary(grouping: numList) { HashablePair($0) }.compactMapValues { $0.count > 1 ? $0.count : nil }
print(counted)

With the help of this beautifier extension:

extension HashablePair: CustomStringConvertible {
    var description: String { "(\(a),\(b))" }
}

Gives a Dictionary of items appearing more than once and their frequency:

[(2,8): 2]
Related