标签:
取一个序列中元素出现的格式
方法一:
from collections import Iterable
def action(iterable):
reslut = {}
if not isinstance(iterable,Iterable): #判断对象是否是可迭代
raise TypeError(‘is not iterable‘) #如果不是手动触发异常
for item in iterable: #对对象进行迭代
if item in reslut.keys(): #把元素和元素出现的次数
reslut[item] += 1 #加到空的reslut字典中
else:
reslut[item] = 1
return reslut
if __name__ == ‘__main__‘:
data = [‘a‘,‘b‘,‘a‘,‘b‘,‘c‘,‘b‘,‘a‘,1,2,1,1,3,3,4,4,1,2,5,5]
reslut = action(data)
print reslut
结果:
{‘a‘: 3, 1: 4, ‘c‘: 1, ‘b‘: 3, 4: 2, 5: 2, 2: 2, 3: 2}
方法二:直接迭代序列,统计元素出现的个数写到字典里面,元素作为key,value是key出现的次数
data = [‘a‘,‘b‘,‘a‘,‘b‘,‘c‘,‘b‘,‘a‘,1,2,1,1,3,3,4,4,1,2,5,5]
reslut = {}
for item in data:
reslut[item] = data.count(item)
else:
print reslut
结果也是一样的
或者直接字典解析
data = [‘a‘,‘b‘,‘a‘,‘b‘,‘c‘,‘b‘,‘a‘,1,2,1,1,3,3,4,4,1,2,5,5]
reslut = { item:data.count(item) for item in data}
print reslut
标签:
原文地址:http://www.cnblogs.com/huangweimin/p/5699916.html