in 取代 or
- >>> if x == 1 or x == 2 or x == 3:
- ... pass
- ...
- >>> if x in (1,2,3):
- ... pass
字典取代多个if else
- def fun(x):
- if x == 'a':
- return 1
- elif x == 'b':
- return 2
- else:
- return None
-
- def fun(x):
- return {"a": 1, "b": 2}.get(x)
有下标索引的列举
- >>> for i, e in enumerate(["a","b","c"]):
- ... print(i, e)
- ...
- 0 a
- 1 b
- 2 c
天生器
留意区排列表推导式,天生器服从更高
- >>> g = (i**2 for i in range(5))
- >>> g
- <generator object <genexpr> at 0x10881e518>
- >>> for i in g:
- ... print(i)
- ...
- 0
- 1
- 4
- 9
- 16
默认字典 defaultdict
- >>> d = dict()
- >>> d['nums']
- KeyError: 'nums'
- >>>
-
- >>> from collections import defaultdict
- >>> d = defaultdict(list)
- >>> d["nums"]
- []
字符串名目化
- >>> lang = 'python'
- >>> f'{lang} is most popular language in the world'
- 'python is most popular language in the world'
列表中呈现次数最多的元素
- >>> nums = [1,2,3,3]
- >>> max(set(nums), key=nums.count)
- 3
-
- 可能
- from collections import Counter
- >>> Counter(nums).most_common()[0][0]
- 3
读写文件
- >>> with open("test.txt", "w") as f:
- ... f.writelines("hello")
判定工具范例,可指定多个范例
- >>> isinstance(a, (int, str))
- True
相同的尚有字符串的 startswith,endswith
- >>> "http://foofish.net".startswith(('http','https'))
- True
- >>> "https://foofish.net".startswith(('http','https'))
- True
__str__ 与 __repr__ 区别
- >>> str(datetime.now())
- '2018-11-20 00:31:54.839605'
- >>> repr(datetime.now())
- 'datetime.datetime(2018, 11, 20, 0, 32, 0, 579521)'
前者对人友爱,可读性更强,,后者对计较机友爱,支持 obj == eval(repr(obj))
行使装饰器
- def makebold(f):
- return lambda: "<b>" + f() + "</b>"
-
- def makeitalic(f):
- return lambda: "<i>" + f() + "</i>"
-
- @makebold
- @makeitalic
- def say():
- return "Hello"
-
- >>> say()
- <b><i>Hello</i></b>
(编辑:湖南网)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|