1

Using Python is there an easier way without writing bunch of loops be able to count the values in a similar way. Perhaps using some library such as itertools groupby?

#original tuple array
[("A","field1"),("A","field1"),("B","field1")]

#output array
[("A","field1", 2), ("B", "field1",1)]
codeBarer
  • 2,238
  • 7
  • 44
  • 75

3 Answers3

4

You can use a Counter dict to group, adding the count at the end

l = [("A","field1"),("A","field1"),("B","field1")]


from collections import Counter


print([k+(v,) for k,v in Counter(l).items()])

If you want the output ordered by the first time you encounter a tuple, you can use an OrderedDict to do the counting:

from collections import OrderedDict

d = OrderedDict()
for t in l:
    d.setdefault(t, 0)
    d[t] += 1

print([k+(v,) for k,v in d.items()])
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
0

You can use itertools.groupby. Omit the key parameter, then it will just group equal elements (assuming those are consecutive), then add the number of elements in the group.

>>> lst = [("A","field1"),("A","field1"),("B","field1")]
>>> [(k + (len(list(g)),)) for k, g in itertools.groupby(lst)]
[('A', 'field1', 2), ('B', 'field1', 1)]

If the elements are not consecitive, then this will not work, and anyway, the solution suggesting collections.Counter seems to be a better fit to the problem.

tobias_k
  • 81,265
  • 12
  • 120
  • 179
0

I guess you just want to count the number of ocurrences of each tuple...right? If so, you can use Counter

Community
  • 1
  • 1
manu
  • 1,333
  • 2
  • 11
  • 24
  • Hi Manu, yet I'm just doing a count. I want to count total of field1 that have "A" and count total field1 in "B" – codeBarer Aug 19 '15 at 09:04