python如何统计元组中重复元素个数
rs = (('192.168.16.1',), ('192.168.41.1',), ('192.168.41.1',))
想得到结果为:192.168.16.1:1,192.168.41.1:2
[解决办法]
c=[]
for n in rs:
if n not in c:
c.append(n)
[解决办法]
Python 2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)] on win32Type "copyright", "credits" or "license()" for more information.>>> rs = (('192.168.16.1',), ('192.168.41.1',), ('192.168.41.1',))>>> d = {}>>> for k in rs: for v in k: if v in d: d[v] += 1 else: d[v] = 1 >>> print d{'192.168.16.1': 1, '192.168.41.1': 2}>>>
[解决办法]
from collections import Counter;rs = (('192.168.16.1',), ('192.168.41.1',), ('192.168.41.1',));print(dict(Counter(rs)));
[解决办法]
>>> from collections import Counter>>> rs= (('192.168.16.1',), ('192.168.41.1',), ('192.168.41.1',))>>> qty=Counter()>>> for item in rs: qty[item[0]]=qty[item[0]]+1>>> dict(qty)