Dengan Python, saya memiliki array,

("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")

Dan saya membutuhkan output dengan menunjukkan hitungan

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

Siapapun tolong bantu aku

1
Rogin Thomas 11 Agustus 2017, 10:07

2 jawaban

Jawaban Terbaik

Anda dapat menggunakan Penghitung dari koleksi.

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]
5
stamaimer 11 Agustus 2017, 07:18

Jika Anda tidak peduli tentang pesanan:

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]))
1
Rahul 11 Agustus 2017, 07:14