0

I have a tuple which consist of a number of teams that I have looped through and stored. The next step for me is to find the duplicates and store only one team, but update the number which indicate how many people are associated with the team.

_teamList = []
    for obj in context['object_list']:
        name = obj.team.name
        number = 1
        _teamList.append((name, number))

A example of a input looks something like:

[("Team bobcat", 1), ("Team Coffe", 1)]

here is the code for just getting the teams and add one to that.

I have tried something like this:

seen = set()
    uniq = []
    for x in _teamList:
        if x not in seen:
            x = 1 + x[1]
            uniq.append(x)
            seen.add(x)

Can anyone give me any tips?

Vlok
  • 63
  • 2
  • 12

3 Answers3

1

You can use 'Counter' from Collections. https://docs.python.org/2/library/collections.html

This will automatically group the identical names for you. You need not calculate the number of occurrences.

For eg:

>>> from collections import Counter as c
>>> a = ('team a', 'team b', 'team a', 'team c', 'team b')
>>> c(a)
Counter({'team a': 2, 'team b': 2, 'team c': 1})
yogi
  • 266
  • 2
  • 11
1

Here's a base Python solution:

a = ('team a', 'team b', 'team a', 'team c', 'team b', 'team b', 'team b')
d = {}

for x in a:
    if x in d.keys():
        d[x] += 1 
    else: 
        d[x] = 1

d
# {'team a': 2, 'team b': 4, 'team c': 1}

If you want the output as a tuple, add:

tuple((name, ct) for name, ct in d.items())
# (('team a', 2), ('team b', 4), ('team c', 1))
andrew_reece
  • 20,390
  • 3
  • 33
  • 58
1

You can refer this solution:

x=('team a', 'team b', 'team a', 'team c', 'team b', 'team b', 'team b')
l = {}
for i in x:
     if i not in l:
         l[i] = 1
     else:
         l[i] = l[i] + 1
data = list(tuple(l.items()))
print(data)
#output as:  [('team a', 2), ('team b', 4), ('team c', 1)]
utks009
  • 573
  • 4
  • 14