Rogin Thomas
Rogin Thomas

Reputation: 772

Python array group count

In Python, I have an array of,

("192.168.1.1","high"),("192.168.1.1","high"),("192.168.1.1","low"),("192.168.1.1","low"),("192.168.1.2","high"),("192.168.1.2","medium")

and I need an output by showing count

("192.168.1.1","high",2),("192.168.1.1","low",2),("192.168.1.2","high",1),("192.168.1.2","medium",1)

anyone please help me

Upvotes: 1

Views: 5911

Answers (2)

stamaimer
stamaimer

Reputation: 6485

You can use Counter from collections.

from collections import Counter

l = [("192.168.1.1","high"),("192.168.1.1","high"),("192.168.1.1","low"),("192.168.1.1","low"),("192.168.1.2","high"),("192.168.1.2","medium")]

counter = Counter(l)

result = [(*key, counter[key]) for key in counter]

Upvotes: 6

Rahul
Rahul

Reputation: 11560

If you don't care about order:

l = [("192.168.1.1","high"),("192.168.1.1","high"),("192.168.1.1","low"),("192.168.1.1","low"),("192.168.1.2","high"),("192.168.1.2","medium")]

list(set([(*t, l.count(t)) for t in l]))

Upvotes: 1

Related Questions