暂时只做笔记,后续整理
更新一些小技巧:
自动给数字前补0
参考:https://www.cnblogs.com/zhanglianbo/p/6202683.html
Python中有一个zfill函数用来给字符串前面补0,非常有用,这个zfill看起来也就是zero fill的缩写吧,看一下如何使用:
n = "123"
s = n.zfill(5)
assert s == '00123'
zfill也可以给负数补0:
n = '-123'
s = n.zfill(5)
assert s == '-0123'
对于纯数字也可以通过格式化的方式来补0:
n = 123
s = '%05d' % n
assert s == '00123'
20181031更新
列表和元组比较
(3,5)<(3,6) => True
[3,5] < [3,6] => True
python风格
conn = None
if conn is not None:
connection = conn
else:
connection = 'default'
=>
connection = conn if conn is not None else 'default'
class方法
@classmethod
func(cls):
@staticmethod
func():
func(self):
any(x)判断x对象是否为空对象,如果都为空、0、false,则返回false,如果不都为空、0、false,则返回true
all(x)如果all(x)参数x对象的所有元素不为0、''、False或者x为空对象,则返回True,否则返回False
-----------------------------------------------------------
class collections.Counter([iterable-or-mapping])
from collections import Counter
# Tally occurrences of words in a list
cnt = Counter()
for word in ['red', 'blue', 'red', 'green', 'blue', 'blue']:
cnt[word] += 1
cnt
# Find the ten most common words in Hamlet
import re
words = re.findall(r'\w+', open('hamlet.txt').read().lower())
Counter(words).most_common(10)
c['sausage'] = 0 # counter entry with a zero count
del c['sausage'] # del actually removes the entry
from collections import namedtuple
Point = nametuple('Point', ['x', 'y'])
p = Point(11, y=22)
p[0], p[1]
p.x, py
t = [11, 22]
p = Point._make(t)
p._asdict()
p._replace(x=33)
p._fields
getattr(p, 'x')
d = {'x': 11, 'y': 22}
Point(**d)
参考网址:https://yiyibooks.cn/xx/python_352/library/collections.html#collections.deque
网友评论