定义函数 定义函数 我们不仅可以调用函数,还可以定义自己的函数
1 2 3 4 5 6 7 8 9 10 11 12 扇形面积计算公式:圆心角度数除以360 乘以pi乘以半径的平方 central_angle_1 = 160 radius_1 = 30 sector_area_1 = central_angle / 360 * 3.14 * radius_1 ** 2 central_angle_2 = 160 radius_2 = 30 sector_area_2 = central_angle_2 / 360 * 3.14 * radius_2 ** 2 print (sector_area_1, sector_area_2)dry don't repeat yourself
1 2 3 4 5 6 7 8 9 10 11 def calculator_sector_1 (central_angle, radius ): sector_area = central_angle / 360 * 3.14 * radius ** 2 print (sector_area) calculator_sector_1(160 , 30 ) def favority_book (title ): print (f"One of my favority books is {title} " ) favority_book("stray birds " )
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 def make_judgement (a, b, c, / ): """判断三条边的长度能否构成三角形""" return a + b > c and b + c > a and a + c > b def make_judgement (a, b, c, / ): """判断三条边的长度能否构成三角形""" return a + b > c and b + c > a and a + c > b print (make_judgement(5 , 3 , 4 ))print (make_judgement(a=5 , b=3 , c=4 )) def make_judgement (*, a, b, c ): """判断三条边的长度能否构成三角形""" return a + b > c and b + c > a and a + c > b print (make_judgement(a=5 , b=3 , c=4 ))
验证码
1 2 3 4 5 6 7 8 9 10 11 import randomimport string ALL_CHARS = string.digits + string.ascii_letters print (type (ALL_CHARS))def generate_code (*, code_len=4 ): """生成指定长度的验证码""" return '' .join(random.sample(ALL_CHARS, code_len)) print (generate_code())
双色球
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 import randomRED_BALLS = [i for i in range (1 , 34 )] BLUE_BALLS = [i for i in range (1 , 17 )] def choose (): """ 生成一组随机号码 :return: 保存随机号码的列表 """ selected_balls = random.sample(RED_BALLS, 6 ) selected_balls.sort() selected_balls.append(random.choice(BLUE_BALLS)) return selected_balls def display (balls ): """ 格式输出一组号码 :param balls: 保存随机号码的列表 """ for ball in balls[:-1 ]: print (f'\033[91m{ball:0 >2d} \033[0m' , end=' ' ) print (f'\033[034m{balls[-1 ]:0 >2d} \033[0m' ) n = int (input ('生成几注号码: ' )) for _ in range (n): display(choose())
偏函数 偏函数是指固定函数的某些参数,生成一个新的函数,这样就无需在每次调用函数时都传递相同的参数。在 Python 语言中,我们可以使用functools模块的partial函数来创建偏函数。例如,int函数在默认情况下可以将字符串视为十进制整数进行类型转换,如果我们修修改它的base参数,就可以定义出三个新函数,分别用于将二进制、八进制、十六进制字符串转换为整数,代码如下所示。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 import functoolsint2 = functools.partial(int , base=2 ) int8 = functools.partial(int , base=8 ) int16 = functools.partial(int , base=16 ) print (int ('1001' )) print (int2('1001' )) print (int8('1001' )) print (int16('1001' )) a = bin (9 )[2 :] b = oct (513 )[2 :] c = hex (4097 )[2 :] print (a, b, c)
lambda匿名函数的用法 lambda 是 Python 中创建匿名函数的一种方式,常用于需要一个小函数但不想单独定义 def 函数的场景。
1 lambda 参数1 , 参数2 , ... : 表达式
lambda 是关键字,用于定义匿名函数。
参数1, 参数2,... 是函数的参数列表,可以有多个参数,也可以没有参数。
: 是参数列表和函数体之间的分隔符。
表达式 是函数的返回值,可以是任意合法的表达式。
相当于
1 2 def 函数名 (参数1 , 参数2 , ... ): return 表达式
最简单的例子:加法 1 2 add = lambda x, y: x + y print (add(2 , 3 ))
等价
1 2 def add (x, y ): return x + y
用作 sorted() 的 key 参数 1 2 3 data = [(1 , 3 ), (2 , 1 ), (4 , 2 )] sorted_data = sorted (data, key=lambda x: x[1 ]) print (sorted_data)
sorted sorted() 是 Python 中用来对可迭代对象进行排序的函数,返回一个新的排序后的列表,不会改变原始数据。
✅ 一、基本语法 1 sorted (iterable, key=None , reverse=False )
iterable:要排序的可迭代对象,如列表、元组、集合等。
key:可选参数,用于指定排序的规则。可以是一个函数,也可以是一个 lambda 表达式。
reverse:可选参数,用于指定排序的顺序。默认为 False,表示升序;如果为 True,表示降序。
✅ 二、简单例子 1. 对列表进行排序 1 2 3 nums = [5 , 2 , 9 , 1 ] sorted_nums = sorted (nums) print (sorted_nums)
2. 字符串列表排序(按字母顺序) 1 2 words = ['banana' , 'apple' , 'cherry' ] print (sorted (words))
3. 反向排序 1 2 nums = [3 , 1 , 4 ] print (sorted (nums, reverse=True ))
4. 按字符串长度排序 1 2 words = ['banana' , 'apple' , 'kiwi' ] print (sorted (words, key=len ))
5. 对字典列表按某个字段排序 1 2 3 4 5 6 7 8 9 10 11 12 13 people = [ {'name' : 'Tom' , 'age' : 25 }, {'name' : 'Jerry' , 'age' : 20 }, {'name' : 'Bob' , 'age' : 30 } ] sorted_people = sorted (people, key=lambda x: x['age' ]) for person in sorted_people: print (person['name' ], person['age' ])