簡體   English   中英

Python數組組數

[英]Python array group count

在Python中,我有一系列

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

我需要通過顯示計數來輸出

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

任何人請幫助我

您可以使用集合中的計數器。

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]

如果您不關心訂單:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM