1

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

4
  • 3
    [(*t, len(t)) for t in array] Commented Aug 11, 2017 at 7:09
  • Can you please show what you've tried, though? Commented Aug 11, 2017 at 7:11
  • @ChristianDean it will add each element for every item occurrence , for example for ("192.168.1.1","high",2) it will appear two times. Commented Aug 11, 2017 at 7:15
  • Note to answers: Please stop answering this question. Questions such as this are to broad and should be closed as such, not answered. See Why would a question that's normally too broad in any other language be okay if it's in Python? for more details. Commented Aug 11, 2017 at 7:20

2 Answers 2

6

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]
Sign up to request clarification or add additional context in comments.

Comments

1

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]))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.