介绍
之前断断续续的看过一点python3新特性,今天在这里给大家总结一下。
环境
Python 3.7.3
Mac 10.15.1
实操
- 格式化字符串f-string
In [1]: a = "my is str"
In [2]: f"{a}"
Out[2]: 'my is str'
In [4]: b = {"user": "qingge"}
In [6]: f"{b['user']}"
Out[6]: 'qingge'
- 类型提示Type hinting
In [7]: def ret_str(a:str) -> bool:
...: return a in "abc"
...:
In [8]: ret_str("c")
Out[8]: True
- 枚举类enum
- 自定义枚举值
In [9]: from enum import Enum, auto
In [16]: class Color(Enum):
...: RED = 1
...: BlUE = 2
...: GREEN = 3
In [17]: list(Color)
Out[17]: [, , ]
- 自增,自定义自增值
In [18]: class AutoName(Enum):
...: def _generate_next_value_(name, start, count, last_values):
...: return name
...:
In [19]: class Color(AutoName):
...: RED = auto()
...: BlUE = auto()
...: GREEN = auto()
...:
In [20]: list(Color)
Out[20]: [, , ]
- 访问方式
In [21]: red = Color.RED
In [22]: red
Out[22]:
In [23]: red = Color.RED.value
In [24]: red
Out[24]: 'RED'
In [26]: for key, value in Color.__members__.items():
...: print(f"key:value => {key}:{value}")
...:
key:value => RED:Color.RED
key:value => BlUE:Color.BlUE
key:value => GREEN:Color.GREEN
- itertools模块
- count
In [40]: from itertools import count
In [41]: for i in count(1):
...: if i > 10:
...: break
...: else:
...: print(i)
...:
1
2
3
4
5
6
7
8
9
10
- cycle
In [45]: from itertools import cycle
In [45]: for i in cycle('A'):
...: print(i)
A
A
A
A
A
A
...
更多的函数,大家可以自己尝试
repeat
chain() p, q, ... p0, p1, ... plast, q0, q1, ... chain('ABC', 'DEF') --> A B C D E F
compress() data, selectors (d[0] if s[0]), (d[1] if s[1]), ...
compress('ABCDEF', [1,0,1,0,1,1]) --> A C E F
dropwhile() pred, seq seq[n], seq[n+1], starting when pred fails
dropwhile(lambda x: x<5, [1,4,6,4,1]) --> 6 4 1
groupby() iterable[, keyfunc] sub-iterators grouped by value of keyfunc(v)
ifilter() pred, seq elements of seq where pred(elem) is True
ifilter(lambda x: x%2, range(10)) --> 1 3 5 7 9
ifilterfalse() pred, seq elements of seq where pred(elem) is False
ifilterfalse(lambda x: x%2, range(10)) --> 0 2 4 6 8
islice() seq, [start,] stop [, step] elements from seq[start:stop:step]
islice('ABCDEFG', 2, None) --> C D E F G
imap() func, p, q, ... func(p0, q0), func(p1, q1), ... imap(pow, (2,3,10), (5,2,3)) --> 32 9 1000
starmap() func, seq func(*seq[0]), func(*seq[1]), ... starmap(pow, [(2,5), (3,2), (10,3)]) --> 32 9 1000
tee() it, n it1, it2 , ... itn splits one iterator into n
takewhile() pred, seq seq[0], seq[1], until pred fails
takewhile(lambda x: x<5, [1,4,6,4,1]) --> 1 4
izip() p, q, ... (p[0], q[0]), (p[1], q[1]), ... izip('ABCD', 'xy') --> Ax By
izip_longest() p, q, ... (p[0], q[0]), (p[1], q[1]), ... izip_longest('ABCD', 'xy', fillvalue='-') --> Ax By C- D-
- LRU缓存,memoization技术
In [46]: from functools import lru_cache
In [46]: from functools import lru_cache
In [47]: @lru_cache(maxsize=512)
...: def fib_memoization(number:int) -> int:
...: if number ==0 : return 0
...: if number ==1 : return 1
...: return fib_memoization(number - 1)
In [49]: import time
In [50]: start = time.time()
In [51]: fib_memoization(40)
Out[51]: 1
In [52]: print(f'Duration:{time.time() - start}s')
Duration:13.406868934631348s
- 分解迭代扩展包
In [53]: a, *b, c = range(5)
In [54]: print(a, b, c)
0 [1, 2, 3] 4
- dataclass
Data class装饰器,用来减少对样板代码的使用,该装饰器会自动生成init()和repr()方法。
class Armor:
def __init__(self, armor:float, description:str, level:int = 1):
self.armor = armor
self.level = level
self.description = description
def power(self) -> float:
return self.armor * self.level
armor = Armor(5.2, "common armor.", 2)
armor.power() #10.4
###使用Data Class实现相同的Armor类
from dataclasses import dataclass
@dataclass
class Armor:
armor : float
description : str
level : int = 1
def power(self) -> float:
return self.armor *self.level
armor = Armor(5.2, "common armor.", 2)
armor.power()
- bisect模块保持列表排序:
这是一个免费的二分查找实现和快速插入有序序列的工具。也就是说,你可以使用:
import bisect
bisect.insort(list, element)
- typing
类型检查,防止运行时出现参数和返回值类型不符合。
作为开发文档附加说明,方便使用者调用时传入和返回参数类型。
该模块加入后并不会影响程序的运行,不会报正式的错误,只有提醒。
**注意:typing模块只有在python3.5以上的版本中才可以使用,pycharm目前支持typing检查OK **
- int,long,float: 整型,长整形,浮点型;
- bool,str: 布尔型,字符串类型;
- List, Tuple, Dict, Set:列表,元组,字典, 集合;
- Iterable,Iterator:可迭代类型,迭代器类型;
- Generator:生成器类型;
In [63]: from typing import List, Tuple, Dict
In [64]: def add(a:int, string:str, f:float, b:bool) -> Tuple[List, Tuple, Dict, bool]:
...: list1 = list(range(a))
...: tup = (string, string, string)
...: d = {"a":f}
...: bl = b
...: return list1, tup, d, bl
...:
...:
...:
In [65]: add(5,"hhhh", 2.3, False)
Out[65]: ([0, 1, 2, 3, 4], ('hhhh', 'hhhh', 'hhhh'), {'a': 2.3}, False)
- 路径管理库 Pathlib
In [68]: from pathlib import Path
In [69]: root = Path('test_path')
In [70]: root
Out[70]: PosixPath('test_path')
In [71]: path = root / 'test_path'
In [72]: path.resolve()
Out[72]: PosixPath('/Users/caiqing/Desktop/test_path/test_path')