一、Counter计数
from collections import Counter
print(Counter("hello world"))
二、从列表中随机取出一个元素
from random import choice
li = [1, 3, 5, 7, 90]
choice(li)
三、反向取值
s = "bicycle"
print(s[::-1])
四、增量操作非原子性
t = (1, 2, [30, 40])
t[2] += [50, 60]
这里会报错
print(t)
(1, 2, [30, 40, 50, 60])
很有趣的东西, 没事的时候可以玩玩
五、ZIP
zip()
函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的列表。
a = [1,2,3]
b = [4,5,6]
zip(a,b)
[(1, 4), (2, 5), (3, 6)]
六、将列表的所有三个值存储在3个新变量中
a = [1, 2, 3]
x, y, z = a
七、嵌套列表转换
import itertools
a = [[1, 2], [3, 4], [5, 6]]
list(itertools.chain.from_iterable(a))
[1, 2, 3, 4, 5, 6]
八、求两数的商和余数
divmod(7, 2)
(3, 1)
九、bytes
中有部分无效的字节
传入errors='ignore'忽略错误的字节
b''.decode('utf-8', errors='ignore')
十、两个字符串的相似度
import difflib
similarity = difflib.SequenceMatcher(None, str1, str2). quick_ratio()
十一、JmesPath
JMESPath使Python处理JSON更加容易,它允许您明确的地指定如何从JSON文档中提取元素。
十二、josn
try:
import simplejson as json
except ImportError:
import json
十三、排序
这个好有趣
list1 = [34, 25, 12, 99, 87, 63, 58, 78, 88, 92]
a = heapq.nlargest(len(list1), list1)
b = heapq.nsmallest(len(list1), list1)