Python内置函数可以减少代码量,在某些场合,效果很明显。例如,设有需求:
列表s中的数据是某市所有中小学教职工新冠疫苗接种比例。统计其中接种比例大于80%且未全员接种的学校数"
s=[0.86,0.06,0.97,0.64,0.77,0.57,0.31,0.17,0.01,0.90,0.00,0.52,0.39,0.57,0.17,
0.35,0.08,0.86,0.35,0.68,0.66,0.78,0.98,0.87,0.09,0.01,0.41,0.86,0.98,0.93,
0.24,0.72,0.54,0.68,0.41,0.04,0.22,0.42,0.84,0.55,0.56,0.77,0.90,0.11,0.50,
0.12,0.02,0.87,0.63,0.50,0.10,0.86,0.06,0.62,0.28,0.43,0.22,0.72,0.47,0.20,
0.29,0.20,0.27,0.64,0.35,0.11,0.08,0.28,0.09,0.71,0.94,0.01,0.31,0.30,0.04,
0.37,0.95,0.82,0.55,0.34,0.62,0.05,0.67,0.09,0.58,0.61,0.73,0.83,0.02,0.91,
0.58,0.51,0.62,0.72,1.00,0.88,0.57,0.93,0.22,0.69,0.81,0.80,0.11,0.98,0.14,
0.47,0.25,0.00,0.36,0.91,0.96,0.31,0.67,0.83,0.68,0.94,0.40,0.84,0.40,0.66,
0.43,0.62,0.77,0.66,0.17,0.78,0.25,0.94,0.30,0.35,0.97,0.00,0.95,0.41,0.93,
0.80,0.22,0.01,0.78,0.71,0.69,0.47,0.71,0.00,0.27,0.38,0.29,0.57,0.96,0.89,
0.47,0.74,0.03,0.43,0.37,0.05,0.30,0.94,0.05,0.11,0.09,0.78,0.98,0.76,0.04,
0.90,0.21,0.54,0.76,0.74,0.18,0.35,0.31,0.42,0.19,0.20,0.81,0.21,0.49,0.23,
0.75,0.28,0.25,0.27,0.20,0.60,0.03,0.76,0.46,0.33,0.03,0.08,0.12,0.87,0.44,
0.65,0.48,0.28,0.69,0.45]
下面的代码都可以实现:
n=len(list(filter(lambda x:1>x>0.8,s)))
print(n)
通过filter函数,将符合条件的筛选,得到的列表元素数
n=len(list(x for x in s if 1>x>0.8))
print(n)
直接用for循环筛选数据
import re
n=len(re.findall(r"(0.[8][1-9]|0.[9][0-9]?)",str(s)))
print(n)
通过正则表达式筛选大于80%的数据,0.80,0.81~0.89 0.90~0.99