- 解析
解析应该会比较常用,先看下面几个例子:
# 字典解析
# 创建一个班级的分数
from random import randint
grades = {'Student{}'.format(i): randint(50, 100) for i in range(1,21)}
print(grades)
# 筛选出高于90分的人
d = {k:v for k, v in grades.items() if v>= 90}
print(len(d))
print(d)
# 字典解析
# 创建一个班级的分数
from random import randint
grades = {'Student{}'.format(i): randint(50, 100) for i in range(1,21)}
print(grades)
# 筛选出高于90分的人
d = {k:v for k, v in grades.items() if v>= 90}
print(len(d))
print(d)
# 集合解析
set1 = {randint(0,65) for i in range(20)}
print(set1)
# 找到能被3整除的
res = {x for x in {randint(0,20) for _ in range(20)} if x%3 == 0}
print(res)
{'Student1': 60, 'Student2': 76, 'Student3': 70, 'Student4': 64, 'Student5': 94, 'Student6': 98, 'Student7': 73, 'Student8': 68, 'Student9': 95, 'Student10': 96, 'Student11': 60, 'Student12': 60, 'Student13': 72, 'Student14': 50, 'Student15': 99, 'Student16': 66, 'Student17': 71, 'Student18': 84, 'Student19': 63, 'Student20': 65}
5
{'Student5': 94, 'Student6': 98, 'Student9': 95, 'Student10': 96, 'Student15': 99}
{'Student1': 94, 'Student2': 97, 'Student3': 52, 'Student4': 54, 'Student5': 96, 'Student6': 66, 'Student7': 67, 'Student8': 96, 'Student9': 65, 'Student10': 57, 'Student11': 84, 'Student12': 57, 'Student13': 90, 'Student14': 89, 'Student15': 93, 'Student16': 56, 'Student17': 74, 'Student18': 88, 'Student19': 97, 'Student20': 50}
7
{'Student1': 94, 'Student2': 97, 'Student5': 96, 'Student8': 96, 'Student13': 90, 'Student15': 93, 'Student19': 97}
{0, 1, 41, 11, 44, 45, 47, 15, 49, 51, 52, 21, 20, 62, 25, 27, 61, 30}
{0, 3, 6, 9, 12, 18}
观察以上例子可以得出:序列可以解析,其格式为:
{返回值 for循环 筛选条件}
其中筛选条件可有可无,同时可大胆猜测列表也可以如此操作!
- 函数定义
格式:
# 格式
# def 函数名(num):
# pass
# 调用函数:
# 函数名(num)
实例:
def caculateNum(num):
"""
计算1~num质检的累加和
:param num:累加和的末尾
:return: 返回累加和
"""
res = 0
for i in range(1,num+1):
res += i
return res
res = caculateNum(100)
print(res)
5050
网友评论