python 判断列表中每个元素有几个

来源:互联网 发布:语音视频聊天软件 编辑:程序博客网 时间:2024/05/21 17:06

使用标准库提供的collections

基本用法:

import collectionslst = []    # lst存放所谓的100万个元素d = collections.Counter(lst)# 瞬间出结果for k in d:    # k是lst中的每个元素    # d[k]是k在lst中出现的次数

from collections import Counterwords = [    'look', 'into', 'my', 'eyes', 'look', 'into', 'my', 'eyes',    'the', 'eyes', 'the', 'eyes', 'the', 'eyes', 'not', 'around', 'the',    'eyes', "don't", 'look', 'around', 'the', 'eyes', 'look', 'into',    'my', 'eyes', "you're", 'under']print (Counter(words))Counter({'eyes': 8, 'the': 5, 'look': 4, 'into': 3, 'my': 3, 'around': 2, 'not': 1, "don't": 1, "you're": 1, 'under': 1})print (Counter(words).most_common(4))[('eyes', 8), ('the', 5), ('look', 4), ('into', 3)]

 参考:点击打开链接


原创粉丝点击