1/ 创建一个数字序列

my_list = []
for i in range(0, 10, 1):
my_list.append(i)


my_list = range(0,10,1)
>>> my_list = [0,1,2,3,4,5,6,7,8,9]


2/ 叠加两个字典

a = {“alpha”: 3, “beta”: 5}
b = {“gamma”: 1, “delta”: 12}

a.update(b)

>>> a = {“alpha”: 3, “beta”: 5, “gamma”: 1, “delta”: 12}


3/ 创建一个序列字典

my_dic = {(x+2): (x**2 + 1) for x in range(4)}

>>> my_dic = {2: 1, 3: 2, 4: 5, 5: 10}


4/ 反转列表

my_list = [1, 2, 3, 4]
my_list = my_list[::-1]

>>> my_list = [4, 3, 2, 1]


5/ 解包一个元组

my_tup = (0, 1, 2, 3)
a, b, c, d = *my_tup

>>> a = 0
>>> b = 1
>>> c = 2
>>> d = 3


6/ 过滤列表

my_list = [1,2,3,4]

def my_filter(x):
if x==3 or x%2==0:
return True
else:
return False

my_list = list(filter(my_filter, my_list))

>>> my_list = [2,3,4]


7/ 从函数返回多个值

def my_func(x)
for i in range(x):
yield x**2

for k in my_func(4):
print(k)

>>> 0
>>> 1
>>> 4
>>> 9


8/导入这个

import this

The Zen of Python
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
. . .


9/ 集合的基本操作

a = {1,2,3}
b = {3,4,5}


# Union
print(a & b)

>>> {1, 2, 3, 4, 5}

# Intersection
print(a | b)

>>> {3}

# Symetric difference
print(a ^ b)

>>> {1, 2, 4, 5}


10/ 代码 if : else : 在一行中

i = 1 if True else 2

>>> i = 1


11/ 限制算法的递归次数

import sys
sys.setrecursionlimit(1000)


12/ 更快地打印文本

import sys
sys.stdout.write(“im Adrien”) # only string


13/ 有一个列表的中间项

l = [1,2,3,4,5,6,7]
a, *b, c = l

>>> a = 1
>>> b = [2,3,4,5,6]
>>> c = 7


14/ 用 _ 分隔大数

1_000_000_000


15/ 交换字典的键/值

my_dic = {“a”: 1, “b”: 2}
my_dic = {v:k for k, v in my_dic.items()}

my_dic = {1: “a”, 2: “b”}