python日常小技巧
1. 根据分数判定等级
用if条件判断感觉很low, 使用bisect瞬间就高大上了(使用二分法来排序)
import bisect as bs
score = [60, 70, 80, 90]
f = "EDCBA"
level = lambda x: f[bs.bisect(score, x)]
print(level(46), level(69), level(76), level(80), level(92))
说明:使用bisect模块的函数前先确保操作的列表是已排序的,有兴趣可以研究下bisect_left和bisect_right
2.写一个字符串转数字的函数类似int
from functools import reduce
num = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
def str2int(s):
return reduce(lambda x, y: x*10+y if y>=0 else x, map(lambda x: num[x] if x in num else -1, s))
print(str2int("12456"))
print(str2int("12e3456e")) # 需要数字开头
3. 杨辉三角
def triangles(num):
def up():
N = [1]
while True:
yield N
N = [1]+[N[n]+N[n-1] for n in range(1, len(N))]+[1]
for t in up():
print(t)
num -= 1
if not num:break
triangles(9)
4. *将迭代器解压出来
由于python3版本为了节约内存很多函数返回值都是生成器,如常用的map, filter等
单有时候我们想要直接获得结果,此时就可以使用*来获得
用*解析出的是多个对象,可以传递给不定长参数,不能做可迭代对象用for 遍历
tmp = ['1', '2', '3']
print(map(int, tmp))
print(*map(int, tmp))
输出
<map object at 0x7ffa09085208>
1 2 3
实例
import string
tmp = ['1', '2', '3']
def get(*args):
for i in (args):
print(i, type(i))
get(*map(int, tmp))
get(*string.ascii_lowercase[:3])
输出
1 <class 'int'>
2 <class 'int'>
3 <class 'int'>
a <class 'str'>
b <class 'str'>
c <class 'str'>
5. rf字符串
f 字符串前面可以直接加r组成r字符串
import re
src = '12+3*5/2'
tmp = {1: "*", 2: "+", 3: '-', 4: "/"}
flags = rf"[{''.join(tmp.values())}]"
print(flags, re.findall(flags, src), re.split(flags, src))
输出
[*+-/] ['+', '*', '/'] ['12', '3', '5', '2']
注意符号循序要按ASCII顺序先后,否则会报错:
sre_constants.error: bad character range ± at position 1*
6. or取代if else
python中使用if else来替代其他语言的 ?: 三目运算,
但如果我们只是判断是否是空值( None, False, 0, 0.0, 0L, ‘’, (), [], {}),我们只需要使用or即可实现,省略了if else的判断
示例: b和c是相同的效果
a = input("输入:")
b = a if a else "none"
c = a or "none"
print(b, c)
7. 字典get默认值的妙用
如下面的例子是统计单词数量, 使用get时设置默认值,可以省去判断get再做添加的麻烦
words = ["shadow", "eason", "go", "shadow", "eason", "go", "", "shu"]
counts = {"shadow": 1}
for word in words:
counts[word]=counts.get(word,0)+1
print(counts)