首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > perl python >

python怎么统计元组中重复元素个数

2012-07-26 
python如何统计元组中重复元素个数rs ((192.168.16.1,), (192.168.41.1,), (192.168.41.1,))想得

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 code
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}>>>
[解决办法]
Python code
from collections import Counter;rs = (('192.168.16.1',), ('192.168.41.1',), ('192.168.41.1',));print(dict(Counter(rs)));
[解决办法]
Python code
>>> 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) 

热点排行