python3 开发面试题(collections中的Counter)6.7
首先我們拿到題目進行需求分析:
1、先獲取數據就是域名??
獲取數據我們可以用正則,或者域名還是有相同點可以用split切分
2、統計域名訪問的次數
可以用Python的內置模塊來統計,
3、然后就是輸出要求的格式
sorted內置函數用來排序
然后開始最輕松的活,開始碼字:
#第一種方式 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)這道題目考了這些知識點,re模塊,匿名函數,內置函數sorted,collections中的Counter
這些在基礎篇都找得到相應的博客,
我們就來說說collections中的Counter
我們直接打開源碼
Counter類的目的是用來跟蹤值出現的次數。它是一個無序的容器類型,以字典的鍵值對形式存儲,其中元素作為key,其計數作為value。計數值可以是任意的Interger(包括0和負數)
再看源碼中的使用方法:
>>> c = Counter('abcdeabcdabcaba') # count elements from a string? ?生成計數對象
>>> c.most_common(3) # three most common elements? ?這里的3是找3個最常見的元素
[('a', 5), ('b', 4), ('c', 3)]
>>> c.most_common(4)? ? ??這里的4是找4個最常見的元素
[('a', 5), ('b', 4), ('c', 3), ('d', 2)]
>>> sorted(c) # list all unique elements? ?列出所有獨特的元素
['a', 'b', 'c', 'd', 'e']
>>> ''.join(sorted(c.elements())) # list elements with repetitions
'aaaaabbbbcccdde'
這里的elements 不知道是什么?那就繼續看源碼:
def elements(self):
'''Iterator over elements repeating each as many times as its count.
迭代器遍歷元素,每次重復的次數與計數相同
>>> sum(c.values()) # total of all counts? ?計數的總和
15
>>> c['a'] # count of letter 'a'? ??字母“a”的數
5
>>> for elem in 'shazam': # update counts from an iterable? 更新可迭代計數在新的可迭代對象
... c[elem] += 1 # by adding 1 to each element's count? ? ??在每個元素的計數中增加1
>>> c['a'] # now there are seven 'a'? ? ? ? ? ? 查看‘a’的計數,加上上面剛統計的2個,總共7個“a”
7
>>> del c['b'] # remove all 'b'? ? ? 刪除所有‘b’的計數
>>> c['b'] # now there are zero 'b'? ? ?
0
>>> d = Counter('simsalabim') # make another counter? ? ?
>>> c.update(d) # add in the second counter? ? ?在第二個計數器中添加
>>> 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:
如果計數被設置為零或減少到零,它將保持不變
在計數器中,直到條目被刪除或計數器被清除:
>>> 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)]
大約就這幾個用法:大家拓展可以自己翻看源碼
轉載于:https://www.cnblogs.com/ManyQian/p/9152002.html
總結
以上是生活随笔為你收集整理的python3 开发面试题(collections中的Counter)6.7的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: urllib使用二
- 下一篇: 讲一下python的背景知识