# counter 統計個數
# -elemenes
# most_common
# -subtract
# defaultdict 字典默認值
# ChainMap 合併多個映射對象(字典)
# OrderDict 有順序的字典
# deque 雙向隊列,可限制長度
# append
# appendleft
# ratote
# namedtuple 命名元組
# collections裏面的幾個方法
from collections import Counter, defaultdict, ChainMap, OrderedDict,deque,namedtuple
s = 'coop loves python'
counter = Counter(s)
counter
Counter({'c': 1,
'o': 4,
'p': 2,
' ': 2,
'l': 1,
'v': 1,
'e': 1,
's': 1,
'y': 1,
't': 1,
'h': 1,
'n': 1})
# counter常用的方法
counter.elements()
"""Signature: counter.elements()
Docstring:
Iterator over elements repeating each as many times as its count.
"""
'Signature: counter.elements()\nDocstring:\nIterator over elements repeating each as many times as its count.\n'
counter.elements()
<itertools.chain at 0x27909def2b0>
list(counter.elements())
['c',
'o',
'o',
'o',
'o',
'p',
'p',
' ',
' ',
'l',
'v',
'e',
's',
'y',
't',
'h',
'n']
counter.most_common()
[('o', 4),
('p', 2),
(' ', 2),
('c', 1),
('l', 1),
('v', 1),
('e', 1),
('s', 1),
('y', 1),
('t', 1),
('h', 1),
('n', 1)]
counter.most_common(3)
[('o', 4), ('p', 2), (' ', 2)]
counter.subtract('o') # 計算個數少一個該元素--u
counter.most_common(4)
[('o', 2), ('p', 2), (' ', 2), ('c', 1)]
s = 'coop loves python so much love you so mucu love so much much '
count_dict = {}
for x in s.split(' '):
if x in count_dict:
count_dict[x] += 1
else:
count_dict[x] = 1
count_dict
{'coop': 1,
'loves': 1,
'python': 1,
'so': 3,
'much': 3,
'love': 2,
'you': 1,
'mucu': 1,
'': 2}
dict_w = defaultdict(int) # ==defaultdict(lambda:0)
for x in s.split(' '):
dict_w[x] +=1
dict_w
defaultdict(int,
{'coop': 1,
'loves': 1,
'python': 1,
'so': 3,
'much': 3,
'love': 2,
'you': 1,
'mucu': 1,
'': 2})
line = [(1,2), (3,4), (1,6), (3,8),(2,6)]
# [3:[4,8], 1:[2, 6]]
pd = {}
for x, y in line:
if x in pd:
pd[x].append(y) # 不用聲明value的類型,此處是列表
else:
pd[x] = [y]
print(pd)
{1: [2, 6], 3: [4, 8], 2: [6]}
pd_default = defaultdict(list)
for x, y in line:
pd_default[x].append(y)
print(pd_default)
defaultdict(<class 'list'>, {1: [2, 6], 3: [4, 8], 2: [6]})
aa = defaultdict()
aa
defaultdict(None, {})
aa['name'] = 'coop'
aa
defaultdict(None, {'name': 'coop'})
#ChainMap
"""
Init signature: ChainMap(*maps)
Docstring:
A ChainMap groups multiple dicts (or other mappings) together
to create a single, updateable view.
"""
'\nInit signature: ChainMap(*maps)\nDocstring: \nA ChainMap groups multiple dicts (or other mappings) together\nto create a single, updateable view.\n'
dict1 = {3:[6,2], 4:[6,7], 5:[7,9]}
dict2 = {'':2, 'coop':2, 'love':3, 'so':3, 'much':8, 'you':9}
chain = ChainMap(dict1, dict2)
chain
ChainMap({3: [6, 2], 4: [6, 7], 5: [7, 9]}, {'': 2, 'coop': 2, 'love': 3, 'so': 3, 'much': 8, 'you': 9})
print(type(chain))
<class 'collections.ChainMap'>
chain['coop'] # 同字典的取值方法一樣 連接字典,並且可以取值
2
chain[3]
[6, 2]
new_dict = {'coop':88, 'love':89}
chain.update(new_dict) # 更新到第一個字典中了
chain
ChainMap({3: [6, 2], 4: [6, 7], 5: [7, 9], 'coop': 88, 'love': 89}, {'': 2, 'coop': 2, 'love': 3, 'so': 3, 'much': 8, 'you': 9})
chain.update(dict2) # key值相同的會被覆蓋掉
chain
ChainMap({3: [6, 2], 4: [6, 7], 5: [7, 9], 'coop': 2, 'love': 3, '': 2, 'so': 3, 'much': 8, 'you': 9}, {'': 2, 'coop': 2, 'love': 3, 'so': 3, 'much': 8, 'you': 9})
order_dict = OrderedDict(dict2) # 按照字母的順序排列 sorted也可做到
order_dict
OrderedDict([('', 2),
('coop', 2),
('love', 3),
('so', 3),
('much', 8),
('you', 9)])
order_dict.items()
odict_items([('', 2), ('coop', 2), ('love', 3), ('so', 3), ('much', 8), ('you', 9)])
sorted(order_dict.items())
[('', 2), ('coop', 2), ('love', 3), ('much', 8), ('so', 3), ('you', 9)]
aa = sorted(order_dict.items())
aa
[('', 2), ('coop', 2), ('love', 3), ('much', 8), ('so', 3), ('you', 9)]
for i in aa:
print(i)
('', 2)
('coop', 2)
('love', 3)
('much', 8)
('so', 3)
('you', 9)
order_dict2 = OrderedDict(sorted(dict2.items())) # 將列表編程了字典
order_dict2
OrderedDict([('', 2),
('coop', 2),
('love', 3),
('much', 8),
('so', 3),
('you', 9)])
for i in order_dict2.items():
print(i)
('', 2)
('coop', 2)
('love', 3)
('much', 8)
('so', 3)
('you', 9)
# deque ---double-ended queue 雙向追加,也可以旋轉
# []
d = deque()
d.append(22)
d.append(33)
d
deque([22, 33])
d.appendleft(88)
d.appendleft(34)
d
deque([34, 88, 22, 33])
d.rotate() # 正--順時針轉動
d
deque([22, 33, 34, 88])
d.rotate(1)
d
deque([88, 22, 33, 34])
d.rotate(-1)
d
deque([22, 33, 34, 88])
#deque?
"""Init signature: deque(self, /, *args, **kwargs)
Docstring:
deque([iterable[, maxlen]]) --> deque object
A list-like sequence optimized for data accesses near its endpoints.
File: c:\users\coop\miniconda3\envs\coop\lib\collections\__init__.py
Type: type"""
File "<ipython-input-100-0feb1a014db8>", line 8
Type: type"""
^
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 197-198: truncated \uXXXX escape
n = range(9)
m = [i for i in range(9)]
m
[0, 1, 2, 3, 4, 5, 6, 7, 8]
deque(m, 4) # 是從後面取值的
deque([5, 6, 7, 8])
tail 文件倒着取多少行
def last_line(filename, n):
with open(filename) as f :
return deque(f,n)
import os
base_dir = r'D:\全棧\全棧資料\第三階段 python進階\文件與日誌-演示代碼\02-auto\data'
log_path = os.path.join(base_dir, 'access.log')
last_line(log_path, 5)
deque(['66.249.65.40 - - [20/May/2010:11:56:51 +0100] "GET /posts/7806/ HTTP/1.1" 200 26858 "-" "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)"\n',
'220.181.7.67 - - [20/May/2010:11:57:38 +0100] "GET / HTTP/1.1" 200 26130 "-" "Baiduspider+(+http://www.baidu.com/search/spider.htm)"\n',
'66.249.65.40 - - [20/May/2010:11:57:55 +0100] "GET /posts/7802/ HTTP/1.1" 200 26507 "-" "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)"\n',
'220.181.94.216 - - [20/May/2010:11:58:47 +0100] "GET / HTTP/1.1" 200 26130 "-" "Sogou web spider/4.0(+http://www.sogou.com/docs/help/webmasters.htm#07)"\n',
'66.249.65.40 - - [20/May/2010:11:59:00 +0100] "GET /posts/7803/ HTTP/1.1" 200 29040 "-" "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)"\n'])
namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(3, 8)
p
Point(x=3, y=8)
p.y
8
p.x
3
p.x = 33
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-118-dac7085722b7> in <module>()
----> 1 p.x = 33
AttributeError: can't set attribute
p.x + p.y
11
poing = namedtuple('poing', 'x y')
p = poing(8 , 9)
p
poing(x=8, y=9)
point = namedtuple('poing', 'm, n')
p = point(9,9)
p
poing(m=9, n=9)
p.m
9