运用字典dict()(引荐进修:Python视频教程)
轮回遍历出一个可迭代对象中的元素,假如字典没有该元素,那末就让该元素作为字典的键,并将该键赋值为1,假如存在就将该元素对应的值加1.
lists = ['a','a','b',5,6,7,5] count_dict = dict() for item in lists: if item in count_dict: count_dict[item] += 1 else: count_dict[item] = 1
运用defaultdict()
defaultdict(parameter)能够接收一个范例参数,如str,int等,但通报进来的范例参数,不是用来束缚值的范例,更不是束缚键的范例,而是当键不存在的话,完成一种值的初始化
defaultdict(int):初始化为 0
defaultdict(float):初始化为 0.0
defaultdict(str):初始化为 ”
from collections import defaultdict lists = ['a', 'a', 'b', 5, 6, 7, 5] count_dict = defaultdict(int) for item in lists: count_dict[item] += 1
运用鸠合(set)和列表(list)
先运用set去重,然后轮回的把每个元素和每个元素对应的次数lists.count(item)构成一个元组放在列表内里
lists = ['a', 'a', 'b', 5, 6, 7, 5] count_set = set(lists) count_list = list() for item in count_set: count_list.append((item,lists.count(item))
更多Python相干技术文章,请接见Python教程栏目举行进修!
以上就是python怎样计数的细致内容,更多请关注ki4网别的相干文章!