1、 两个变量值互换
a = 1
b = 2
a,b = b,a
print("%d,%d" %(a, b)) # 2, 1
2、 连续赋值
a = b = c = 50
3、 自动解包
a,b,c = [1,2,3] # a=1 b=2 c=3
a, *others = [1,2,3,4] # a=1 others=[2, 3, 4]
4、 链式比较
a = 15
if (10 < a < 20):
print("Hi")
等价于
a = 15
if (a>10 and a<20):
print("Hi")
5、 重复列表
print([5,2]*4) # [5, 2, 5, 2, 5, 2, 5, 2]
6、重复字符串
print("flowerflowerflower"*3) # flowerflowerflower
7、三目运算
age = 30
slogon = "牛逼" if age == 30 else "niubility"
等价于
if age == 30:
slogon = "牛逼"
else:
slogon = "niubility"
8、字典合并
a= {"a":1}
b= {"b":2}
print({**a, **b}) # {'a': 1, 'b': 2}
9、字符串反转
s = "i love python"
print(s[::-1]) # 'nohtyp evol i'
10、列表转字符串
s = ["i", "love", "pyton"]
print(" ".join(s)) # 'i love pyton'
11、for else 语句
检查列表foo是否有0,有就提前结束查找,没有就是打印“未发现"
status = False
for i in foo:
if i == 0:
status = True
break
if not status:
print("未发现")
使用for else 语法
for i in foo:
if i == 0:
break
else:
print("未发现")
12、字典推导式
m = {x: x**2 for x in range(5)}
print(m) # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
13、用Counter查找列表中出现最多的元素
from collections import Counter
content = ["a", "b", "c", "a", "d", "c", "a"]
c = Counter(content)
print(c.most_common(1)) # [('a', 3)] 出现第1多的元素是a,一共出现3次
14、默认值字典
给字典中的value设置为列表,普通方法
d = dict()
if 'a' not in d:
d['a'] = []
d['a'].append(1)
使用defaultdict
默认字典构建一个初始值为空列表的字典
from collections import defaultdict
d = defaultdict(list)
d['a'].append(1)
15、默认表达
import re
data = "hello123world"
match = re.search("(\d+)", data) # 3
if match: # 4
num = match.group(1)
else:
num = None
print(num) # "123"
第3、4行 可以合并成一行代码
if match:=re.search("(\d+)", data):
num = match.group(1)
else:
num = None
print(num) # "123"
16、isinstance
isinstance
函数可用于判断实例的类型,其实第二个参数可以是多个数据类型组成的元组。例如
isinstance(x, (int, float))
# 等价于
isinstance(x, int) or isinstance(x, float)
类似的函数还有字符串的startswith,endswith,例如:
s.startswith(('"""', "'''"))
# 等价于
s.startswith("'''") or s.startswith('"""')
17、用 http.server 共享文件
# python2
python -m SimpleHTTPServer 8000
# python3
python3 -m http.server
效果如下,可以在浏览器共享文件目录,方便在局域网共享文件
18、zip 函数实现字典键值对互换
lang = {"python":".py", "java":".java"}
print(dict(zip(lang.values(), lang.keys()))) # {'.java': 'java', '.py': 'python'}
19、查找列表中出现次数最多的数字
count_list = [1, 2, 3, 4, 2, 2, 3, 1, 4, 4, 4, 5]
print(max(set(test), key=test.count)) # 4
20、使用 slots 节省内存
import sys
class MyClass(object):
def __init__(self, name, identifier):
self.name = name
self.identifier = identifier
self.set_up()
print(sys.getsizeof(MyClass)) # 1064
class MyClass(object):
__slots__ = ['name', 'identifier']
def __init__(self, name, identifier):
self.name = name
self.identifier = identifier
self.set_up()
print(sys.getsizeof(MyClass)) # 896
21、扩展列表
i = ['a','b','c']
i.extend(['e','f','g'])
print(i) # ['a', 'b', 'c', 'e', 'f', 'g']
22、列表负数索引
a = [ 1, 2, 3]
print(a[-1]) # 3
23、列表切片
a = [0,1,2,3,4,5,6,7,8,9]
print(a[3:6]) # [3, 4, 5] 第3个到第6个之间的元素
print(a[:5]) # [0, 1, 2, 3, 4] 前5个元素
print(a[5:]) # [5, 6, 7, 8, 9] 后5个元素
print(a[::]) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] # 所有元素(拷贝列表)
print(a[::2]) # [0, 2, 4, 6, 8] # 偶数项
print(a[1::2]) # [1, 3, 5, 7, 9] # 奇数项
print(a[::-1]) # [9, 8, 7, 6, 5, 4, 3, 2, 1, 0] 反转列表
24、二维数组变一维数组
import itertools
a = [[1, 2], [3, 4], [5, 6]]
i = itertools.chain(*a)
print(list(i)) # [1, 2, 3, 4, 5, 6]
25、有索引的迭代
a = ['Merry', 'Christmas ', 'Day']
for i, x in enumerate(a):
print '{}: {}'.format(i, x) # 0: Merry 1: Christmas 2: Day
26、列表推导式
le = [x*2 for x in range(10)]
print(le) # [0, 2, 4, 6, 8, 10, 12, 14, 16, 18] 每个数乘以2
le = [x for x in range(10) if x%2 == 0]
print(le) # [0, 2, 4, 6, 8] 获取偶数项
27、生成器表达式
ge = (x*2 for x in range(10))
print(ge) # <generator object <genexpr> at 0x01948A50>
print(next(ge)) # 0
print(next(ge)) # 2
print(next(ge)) # 4
print(next(ge)) # Traceback (most recent call last): StopIteration
28、集合推导式
nums = {n**2 for n in range(10)}
print(nums) # {0, 1, 64, 4, 36, 9, 16, 49, 81, 25}
29、判断key是否存在字典中
d = {"1":"a"}
print(d['2']) # Traceback (most recent call last): KeyError: '2'
print('1' in d) # True
print(d['1']) # 'a'
print(d.get("1")) # 'a'
print(d.get("2"))
30、装饰器
from functools import wraps
def tags(tag_name):
def tags_decorator(func):
@wraps(func)
def func_wrapper(name):
return "<{0}>{1}</{0}>".format(tag_name, func(name))
return func_wrapper
return tags_decorator
@tags("html")
def get_text(name):
return "Hello " + name
print(get_text("Python")) # <html>Hello Python</html>
31、字典子集
def sub_dicts(d, keys):
return {k:v for k, v in d.items() if k in keys}
print(sub_dicts({1:"a", 2:"b", 3:"c"}, [1,2])) # {1: 'a', 2: 'b'}
32、反转字典
d = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
print(zip(d.values(), d.keys())) # <zip object at 0x019136E8>
z = zip(d.values(), d.keys())
print(dict(z)) # {1: 'a', 2: 'b', 3: 'c', 4: 'd'}
33、具名元组
from collections import namedtuple
Point = namedtuple("Point", "x,y")
p = Point(x=1, y=2)
print(p.x) # 1
print(p[0]) # 1
print(p.y) # 2
print(p[1]) # 2
34、设置字典默认值
d = dict()
if 'a' not in d:
d['a'] = []
d['a'].append(1)
print(d) # {'a': [1]}
d.setdefault('b',[]).append(2)
print(d) # {'a': [1], 'b': [2]}
35、有序字典
d = dict((str(x), x) for x in range(10))
print(d.keys()) # dict_keys(['0', '1', '5', '9', '4', '6', '7', '8', '2', '3']) key 无序
from collections import OrderedDict
m = OrderedDict((str(x), x) for x in range(10))
print(m.keys()) # odict_keys(['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']) # key 按照插入的顺序排列
36、列表中最大最小的前n个数
import heapq
a = [51, 95, 14, 65, 86, 35, 85, 32, 8, 98]
print(heapq.nlargest(5,a)) # [98, 95, 86, 85, 65]
print(heapq.nsmallest(5,a)) # [8, 14, 32, 35, 51]
37、打开文件
with open('foo.txt', 'w') as f:
f.write("hello")
38、两个列表组合成字典
list_1 = ["One","Two","Three"]
list_2 = [1,2,3]
dictionary = dict(zip(list_1, list_2))
print(dictionary) # {'One': 1, 'Two': 2, 'Three': 3}
39、去除列表中重复元素
my_list = [1,4,1,8,2,8,4,5]
my_list = list(set(my_list))
print(my_list) # [1, 2, 4, 5, 8]
40、打印日历
import calendar
print(calendar.month(2021, 1))
August 2021
Mo Tu We Th Fr Sa Su
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31
41、匿名函数
def add(a, b):
return a+b
等价于
add = lambda a,b:a+b
print(add(1,2)) # 3