# Python-100-Days-CheatSheet
百日python,路线:语法->爬虫->网站->数据科学->机器学习->深度学习
## Day 01:语法
python原生封装的数据结构,按`增删改查`组织
列表
----
```python
<list> = <list>[from_inclusive : to_exclusive : step_size]
<list>.append(<el>)
<list>.extend(<collection>)
<list> += [<el>]
<list> += <collection>
```
```python
<list>.sort()
<list>.reverse()
<list> = sorted(<collection>)
<iter> = reversed(<list>)
```
```python
sum_of_elements = sum(<collection>)
elementwise_sum = [sum(pair) for pair in zip(list_a, list_b)]
sorted_by_second = sorted(<collection>, key=lambda el: el[1])
sorted_by_both = sorted(<collection>, key=lambda el: (el[1], el[0]))
flattened_list = list(itertools.chain.from_iterable(<list>))
list_of_chars = list(<str>)
product_of_elems = functools.reduce(lambda out, x: out * x, <collection>)
no_duplicates = list(dict.fromkeys(<list>))
```
```python
index = <list>.index(<el>) # 返回第一个匹配 <el> 的索引
<list>.insert(index, <el>) # 在 index 处插入为 <el>,右边元素右移
<el> = <list>.pop([index]) # 移除 index 处的 <el> ,默认移除列表的最后一个元素
<list>.remove(<el>) # 移除第一次出现的 <el>
<list>.clear() # 移除所有
```
字典
----------
```python
<view> = <dict>.keys()
<view> = <dict>.values()
<view> = <dict>.items()
```
```python
value = <dict>.get(key, default) # key 不存在则返回 default 默认值
value = <dict>.setdefault(key, default) # 同上,同时给 dict 指定对应 key 的 default 默认值
<dict> = collections.defaultdict(<type>) # 创建一个字典,值的默认类型为 <type>
<dict> = collections.defaultdict(lambda: 1) # 创建一个字典,默认值为 1
```
```python
<dict>.update(<dict>) # 或: dict_a = {**dict_a, **dict_b}.
<dict> = dict(<list>) # 用键值对列表初始化一个字典
<dict> = dict(zip(keys, values)) # 用两个列表初始化一个字典
<dict> = dict.fromkeys(keys [, value]) # 用键列表初始化一个字典
```
```python
value = <dict>.pop(key) # 移除 key,返回被移除的值
{k: v for k, v in <dict>.items() if k in keys} # 按多个 key 过滤字典
```
### Counter 计数器
```python
>>> from collections import Counter
>>> colors = ['blue', 'red', 'blue', 'yellow', 'blue', 'red']
>>> counter = Counter(colors)
Counter({'blue': 3, 'red': 2, 'yellow': 1})
>>> counter.most_common()[0][0]
'blue'
```
Set
---
```python
<set> = set()
<set>.add(<el>)
<set>.update(<collection>)
<set> |= {<el>}
<set> |= <set>
```
```python
<set> = <set>.union(<coll.>) # 或: <set> | <set>
<set> = <set>.intersection(<coll.>) # 或: <set> & <set>
<set> = <set>.difference(<coll.>) # 或: <set> - <set>
<set> = <set>.symmetric_difference(<coll.>) # 或: <set> ^ <set>
<bool> = <set>.issubset(<coll.>) # 或: <set> <= <set>
<bool> = <set>.issuperset(<coll.>) # 或: <set> >= <set>
```
```python
<set>.remove(<el>) # 有错误会抛出.
<set>.discard(<el>) # 不会抛出错误
```
### Frozenset
#### 是否可作为字典的键
```python
<frozenset> = frozenset(<collection>)
```
Range
-----
```python
range(to_exclusive)
range(from_inclusive, to_exclusive)
range(from_inclusive, to_exclusive, step_size)
range(from_inclusive, to_exclusive, -step_size)
```
```python
from_inclusive = <range>.start
to_exclusive = <range>.stop
```
Enumerate
---------
```python
for i, el in enumerate(<collection> [, i_start]):
...
```
自定义名字的元组
-----------
```python
>>> Point = collections.namedtuple('Point', 'x y')
>>> p = Point(1, y=2)
Point(x=1, y=2)
>>> p[0]
1
>>> p.x
1
>>> getattr(p, 'y')
2
>>> p._fields # 或: Point._fields
('x', 'y')
```
Iterator
--------
```python
<iter> = iter(<collection>)
<iter> = iter(<function>, to_exclusive)
```
#### 读取输入,空行停止
```python
for line in iter(input, ''):
...
```
#### 同上,每次在输入前加一条信息,不计入读取的输入
```python
from functools import partial
for line in iter(partial(input, 'Please enter value: '), ''):
...
```
### Next
**返回下一个元素。 如果没下一个元素了,抛出错误或返回 default**
```python
<el> = next(<iter> [, default])
```
#### Skips first item:
```python
next(<iter>)
for element in <iter>:
...
```
Generator
---------
**方便实现迭代协议**
```python
def step(start, step_size):
while True:
yield start
start += step_size
```
```python
>>> stepper = step(10, 2)
>>> next(stepper), next(stepper), next(stepper)
(10, 12, 14)
```
Type
----
```python
<type> = type(<el>) # <class 'int'> / <class 'str'> / ...
```
```python
from numbers import Number, Integral, Real, Rational, Complex
<bool> = isinstance(<el>, Number)
```
```python
<bool> = callable(<el>)
```
String
------
```python
<str> = <str>.strip() # 移除 <str> 首尾两边的空白字符
<str> = <str>.strip('<chars>') # 移除 <str> 首尾两边由 <chars> 指定的字符
```
```python
<list> = <str>.split() # 按空格字符切分成列表
<list> = <str>.split(sep=None, maxsplit=-1) # 按 'sep' 字符串切分成列表,至多 'maxsplit' 次.
<str> = <str>.join(<list>) # 以 <str> 为分隔符合并 <list> 的所有元素.
```
```python
<str> = <str>.replace(old_str, new_str)
<bool> = <str>.startswith(<sub_str>) # 可以传字符串元组
<bool> = <str>.endswith(<sub_str>) # 可以传字符串元组
<int> = <str>.index(<sub_str>) # 返回子串的第一个索引
<bool> = <str>.isnumeric() # <str> 含数字则返回 True
<list> = textwrap.wrap(<str>, width) # 漂亮地将字符串折叠成行
```
### Char
```python
<str> = chr(<int>) # int 转换成 unicode
<int> = ord(<str>) # unicode 转换成 int.
```
```python
>>> ord('0'), ord('9')
(48, 57)
>>> ord('A'), ord('Z')
(65, 90)
>>> ord('a'), ord('z')
(97, 122)
```
Regex
-----
```python
import re
<str> = re.sub(<regex>, new, text, count=0) # 替换所有
<list> = re.findall(<regex>, text) # 返回所有匹配的字符串
<list> = re.split(<regex>, text, maxsplit=0) # 按正则表达式来切缝字符串
<Match> = re.search(<regex>, text) # 找第一次出现正则表达式匹配的
<Match> = re.match(<regex>, text) # 只在 text 的开始找
<iter> = re.finditer(<regex>, text) # 返回所有匹配的对象,是个迭代器
```
* **参数 `'flags=re.IGNORECASE'` 可以和所有函数一起使用.**
* **参数 `'flags=re.DOTALL'` 让点也匹配行.**
* **使用 `r'\1'` 或 `'\\\\1'` 匹配退格符.**
* **使用 `'?'` 实现非贪心.**
### Match Object
```python
<str> = <Match>.group() # Whole match.
<str> = <Match>.group(1) # Part in first bracket.
<tuple> = <Match>.groups() # All bracketed parts.
<int> = <Match>.start() # <Match> 的头索引
<int> = <Match>.end() # <Match> 的尾索引
```
### Special Sequences
**Use capital letter for negation.**
```python
'\d' == '[0-9]' # 匹配数字
'\s' == '[ \t\n\r\f\v]' # 匹配空白字符
'\w' == '[a-zA-Z0-9_]' # 匹配字母表
```
字符串格式化
------
```python
<str> = f'{<el_1>}, {<el_2>}'
<str> = '{}, {}'.format(<el_1>, <el_2>)
```
```python
>>> Person = namedtuple('Person', 'name height')
>>> person = Person('Jean-Luc', 187)
>>> f'{person.height:10}'
' 187'
>>> '{p.height:10}'.format(p=person)
' 187'
```
### 基本操作
```python
{<el>:<10}