-1

Input- [(0, 48), (0, 1474), (1, 2709), (1, 27), (1, 2)]

Output- [(0, 2), (1, 3)]

Output is computed by counting how many times did the first number in the tuple repeated in the list. My constraint is that I don't want to use Pandas. I have tried collections.Counter(x[0] for x in tuples) but it only gives me a list of [2, 3]. This is insufficient because there is no way to tell what element occurred 2 times or 3 times. How should I do that?

Aran-Fey
  • 39,665
  • 11
  • 104
  • 149
Sankalp
  • 1,182
  • 2
  • 17
  • 22
  • Just out of curiosity, how is Pandas "not pythonic" ? – DeepSpace May 01 '18 at 08:41
  • Also, this is not what `groupby` is for. You should probably use `collections.Counter` – DeepSpace May 01 '18 at 08:42
  • @DeepSpace maybe you're correct but I can't use Pandas here. Business constraint. – Sankalp May 01 '18 at 08:44
  • Please provide input and expected output – DeepSpace May 01 '18 at 08:46
  • @DeepSpace input is in the image. Its the object value seen in Pycharm debug mode. The output is `[(0, 2), (1, 3), (2, 13)]` – Sankalp May 01 '18 at 08:47
  • The thing is, some copy-pasteable input in text format would be much handier than a screenshot of input. – Aran-Fey May 01 '18 at 08:51
  • @Aran-Fey I'm sorry. I understand what you mean. I'm updating the question. – Sankalp May 01 '18 at 08:53
  • [Related](https://stackoverflow.com/questions/11829422/counting-element-occurences-in-nested-lists). There's nothing wrong with using `Counter(x[0] for x in tuples)`, the problem comes afterwards - you're extracting only the values from it, instead of `(key, value)` tuples. I'm tempted to find a *"how to get `(key, value)` pairs from a dict"* duplicate... – Aran-Fey May 01 '18 at 08:59

1 Answers1

2

Counter(x[0] for x in tuples) but it only gives me a list of [2, 3]

This observation is wrong.

from collections import Counter

li = [(0, 48), (0, 1474), (1, 2709), (1, 27), (1, 2)]
print(Counter(x[0] for x in li))
# Counter({1: 3, 0: 2})

Counter always returns a dictionary. To get the output you want you simply need to sort by the keys and create the tuples you want (assuming that this is indeed the order you want your output to be in):

from collections import Counter

li = [(0, 48), (0, 1474), (1, 2709), (1, 27), (1, 2)]
counter = Counter(x[0] for x in li)
output = [(k, v) for k, v in sorted(counter.items(), key=lambda tup: tup[0])]
print(output)
# [(0, 2), (1, 3)]
DeepSpace
  • 78,697
  • 11
  • 109
  • 154
  • 2
    The key function looks redundant. You'll get the same result with a simple `sorted(counter.items())`. – Aran-Fey May 01 '18 at 09:03