python3 开发面试题(collections中的Counter)6.7
首先我們拿到題目進(jìn)行需求分析:
1、先獲取數(shù)據(jù)就是域名??
獲取數(shù)據(jù)我們可以用正則,或者域名還是有相同點(diǎn)可以用split切分
2、統(tǒng)計(jì)域名訪問的次數(shù)
可以用Python的內(nèi)置模塊來統(tǒng)計(jì),
3、然后就是輸出要求的格式
sorted內(nèi)置函數(shù)用來排序
然后開始最輕松的活,開始碼字:
#第一種方式 import re from collections import Counter with open("xx.log","r",encoding="utf-8") as f:data=f.read()res=re.findall(r"https://(.*?)/.*?",data)dic=Counter(res)ret=sorted(dic.items(),key=lambda x:x[1],reverse=True)for k,v in ret:print(v,k)#第二種方式 dic={} with open("xx.log","r",encoding="utf-8") as f:for line in f:line=line.split("/")[2]if line not in dic:dic[line]=1else:dic[line]+=1 ret=sorted(dic.items(),key=lambda x:x[1],reverse=True) for k,v in ret:print( v,k)這道題目考了這些知識(shí)點(diǎn),re模塊,匿名函數(shù),內(nèi)置函數(shù)sorted,collections中的Counter
這些在基礎(chǔ)篇都找得到相應(yīng)的博客,
我們就來說說collections中的Counter
我們直接打開源碼
Counter類的目的是用來跟蹤值出現(xiàn)的次數(shù)。它是一個(gè)無序的容器類型,以字典的鍵值對(duì)形式存儲(chǔ),其中元素作為key,其計(jì)數(shù)作為value。計(jì)數(shù)值可以是任意的Interger(包括0和負(fù)數(shù))
再看源碼中的使用方法:
>>> c = Counter('abcdeabcdabcaba') # count elements from a string? ?生成計(jì)數(shù)對(duì)象
>>> c.most_common(3) # three most common elements? ?這里的3是找3個(gè)最常見的元素
[('a', 5), ('b', 4), ('c', 3)]
>>> c.most_common(4)? ? ??這里的4是找4個(gè)最常見的元素
[('a', 5), ('b', 4), ('c', 3), ('d', 2)]
>>> sorted(c) # list all unique elements? ?列出所有獨(dú)特的元素
['a', 'b', 'c', 'd', 'e']
>>> ''.join(sorted(c.elements())) # list elements with repetitions
'aaaaabbbbcccdde'
這里的elements 不知道是什么?那就繼續(xù)看源碼:
def elements(self):
'''Iterator over elements repeating each as many times as its count.
迭代器遍歷元素,每次重復(fù)的次數(shù)與計(jì)數(shù)相同
>>> sum(c.values()) # total of all counts? ?計(jì)數(shù)的總和
15
>>> c['a'] # count of letter 'a'? ??字母“a”的數(shù)
5
>>> for elem in 'shazam': # update counts from an iterable? 更新可迭代計(jì)數(shù)在新的可迭代對(duì)象
... c[elem] += 1 # by adding 1 to each element's count? ? ??在每個(gè)元素的計(jì)數(shù)中增加1
>>> c['a'] # now there are seven 'a'? ? ? ? ? ? 查看‘a(chǎn)’的計(jì)數(shù),加上上面剛統(tǒng)計(jì)的2個(gè),總共7個(gè)“a”
7
>>> del c['b'] # remove all 'b'? ? ? 刪除所有‘b’的計(jì)數(shù)
>>> c['b'] # now there are zero 'b'? ? ?
0
>>> d = Counter('simsalabim') # make another counter? ? ?
>>> c.update(d) # add in the second counter? ? ?在第二個(gè)計(jì)數(shù)器中添加
>>> c['a'] # now there are nine 'a'? ? ?
9
>>> c.clear() # empty the counter? ? qingg
>>> c
Counter()
Note: If a count is set to zero or reduced to zero, it will remain
in the counter until the entry is deleted or the counter is cleared:
如果計(jì)數(shù)被設(shè)置為零或減少到零,它將保持不變
在計(jì)數(shù)器中,直到條目被刪除或計(jì)數(shù)器被清除:
>>> c = Counter('aaabbc')
>>> c['b'] -= 2 # reduce the count of 'b' by two
>>> c.most_common() # 'b' is still in, but its count is zero
[('a', 3), ('c', 1), ('b', 0)]
大約就這幾個(gè)用法:大家拓展可以自己翻看源碼
轉(zhuǎn)載于:https://www.cnblogs.com/ManyQian/p/9152002.html
總結(jié)
以上是生活随笔為你收集整理的python3 开发面试题(collections中的Counter)6.7的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: urllib使用二
- 下一篇: 讲一下python的背景知识