IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> Python知识库 -> 学习python第十四天 -> 正文阅读

[Python知识库]学习python第十四天

学习python第十四天

首先,思考一个问题:

如果要写一个函数,但是函数参数的个数暂时无法确定,有可能没有,
有可能有很多个参数,应该怎么办?请预习我发的文档,回答这个问题

可变参数

*args可变参数----->直接接受零个或任意多个位置参数---->将所有位置上的餐数打包成一共元组
**kwargs----->可以接收零个或任意多个关键字参数---->将所有的关键字参数打包出一个字典

在参数前家星号

这两个单词可以换,但是不建议换,因为高手都用这个,

简单示例

加入我们要计算随机的个数的不同数字的和

def add(*args):
    total = 0
    for arg in args:
        total += arg
    return total
    

计算字典值的和也是一样的到理

def add(**kwargs):
    total = 0
    for value in kwargs.values():
        total += value
    return total

累乘就将运算符号变一下即可

但是如果我们输入字典和数字或者其他东西呢怎么处理呢,首先可能是汉字肯定不能加减乘除

其次字典的值也不一定就是数字

def add(*args, **kwargs):
    total = 0
    for arg in args:
        if type(arg) in (int, float):
            # 判断是否为数字
            total += arg
    for value in kwargs.values():
        if type(value) in (int, float):
            # 同上
            total += value
    return total


def mul(*args, **kwargs):
    # def add(*args):
    total = 1
    for arg in args:
        if type(arg) in (int, float):
            total *= arg
    for value in kwargs.values():
        if type(value in (int, float)):
            total *= value
    return total

在python中,函数是很重要的存在,

在Python中的函数是一等函数(一等公民):
1、函数可以作为函数的参数,
2、函数可以作为函数的返回值
3、函数可以赋值给变量
如果把函数作为函数的参数或返回值,这种玩法通常被称为高阶函数

在在函数中调用函数,我们首先把上面那个为例

def add(*args, **kwargs):
    total = 0
    for arg in args:
        if type(arg) in (int, float):
            total += arg
    for value in kwargs.values():
        if type(value) in (int, float):
            total += value
    return total

基于函数耦合性问题我们将加减乘除重新定义出函数

def add(x, y):
    return x + y


def mul(x, y):
    return x * y


def sub(x, y):
    return x - y


def truediv(x, y):
    return x / y


我们只要使用这些函数就可以快速实现上面函数的不同运算

def calculate(init_value, fn, *args, **kwargs):
    # init_value为我们针对不同运算设定的total初始值
    # fn 为不同运算对应的参数,注意这里传入函数作为参数时不能加上括号
    # *args, **kwargs就是计算的参数
    total = init_value
    for arg in args:
        if type(arg) in (int, float):
            total = fn(total, arg)
    for value in kwargs.values():
        if type(value) in (int, float):
            total = fn(total, value)
    return total

def add(x, y):
    return x + y


def mul(x, y):
    return x * y


def sub(x, y):
    return x - y


def truediv(x, y):
    return x / y


# 使用示例
if __name__ == '__main__':
    print(calculate(0, add, 11, 22, 33, 44))
    print(calculate(1, mul, 11, 22, 33, 44))
    print(calculate(100, sub, 11, 22, 33, 44))
    print(calculate(100, truediv, 11, 22, 33, 44))
#输出结果
110
351384
-10
0.00028458893973544615

其实那些加减乘除函数python库里面有,可以直接调用,我们这里只是用以案例讲解,如果直接调用

import operator



def calculate(init_value, fn, *args, **kwargs):
    total = init_value
    for arg in args:
        if type(arg) in (int, float):
            total = fn(total, arg)
    for value in kwargs.values():
        if type(value) in (int, float):
            total = fn(total, value)
    return total

if __name__ == '__main__':
    print(calculate(0, operator.add, 11, 22, 33, 44))
    print(calculate(1, operator.mul, 11, 22, 33, 44))
    print(calculate(100, operator.sub, 11, 22, 33, 44))
    print(calculate(100, operator.truediv, 11, 22, 33, 44))

如果需要,其实我们还可以将我们需要的函数这样写,写在这里

同样针对上面那个函数

直接将函数用生成式写法写在参数后面,不过函数的参数对应位置就要改成这样,否则就会报错

def calculate(*args, fn, init_value, **kwargs):


print(calculate(11, 22, 33, 44, init_value=0, fn=lambda x, y: x + y))
print(calculate(11, 22, 33, 44, init_value=1, fn=lambda x, y: x * y))
op = lambda x, y: x - y
print(calculate(11, 22, 33, 44, init_value=100, fn=op))
op = lambda x, y: x / y
print(calculate(11, 22, 33, 44, init_value=100, fn=op))

用函数写冒泡排序

def bubble_sort(items: list, ascending=True, gt=lambda x, y: x > y):
    """

    :param items: 带排序列表
    :param ascending: 是否使用升序,默认为升序
    :param gt: 比较两个元素大小的函数
    :return: 排序后的列表
    """
    items = items[:]
    for i in range(1, len(items)):
        change = False
        for j in range(0, len(items) - i):
            if gt(items[j], items[j + 1]):
                items[j], items[j + 1] = items[j + 1], items[j]
                change = True
        if not change:
            break
    if not ascending:
        items = items[::-1]
    return items


if __name__ == '__main__':
    nums = [23, 45, 65, 12, 2, 23, 73, 3, 15]
    count = ['apple', 'watermelon', 'blueberry', 'orange', 'peer']
    print(bubble_sort(nums, False))
    print(bubble_sort(count, True, gt=lambda x, y: len(x) > len(y)))
    # 这里改变函数里函数的比较方法可以改变字符串的排序方法

练习

查找排好升序列表里面的元素,找到了就返回索引,找不到就返回-1

要求使用冒泡排序

思路和我之前写的那个计算机猜人设定的数字方法大致相同

我们将比较大小的部分转换成函数写在传入参数那里

def seq_search(items: list, key, gt=lambda x, y: x > y):
    """

    :param items:
    :param key:
    :param gt:
    :return:
    """
    nums = items
    start = 0
    end = len(items) - 1

    while start <= end:
        # 如果start大于end说明已经找完了噻,就说明没有资格数,就返回-1
        mid = (start + end) // 2
        if gt(nums[mid], key):
            end = mid - 1

        elif gt(key, nums[mid]):
            start = mid + 1

        else:
            return mid

    return -1


if __name__ == '__main__':
    nums = [3, 15, 16, 28, 46, 49, 58, 69, 73, 76, 78]
    print(seq_search(nums, 106))
    print(seq_search(nums, 73))

函数是python编程里很重要的一个部分,一定要多加练习,练习才是王道

  Python知识库 最新文章
Python中String模块
【Python】 14-CVS文件操作
python的panda库读写文件
使用Nordic的nrf52840实现蓝牙DFU过程
【Python学习记录】numpy数组用法整理
Python学习笔记
python字符串和列表
python如何从txt文件中解析出有效的数据
Python编程从入门到实践自学/3.1-3.2
python变量
上一篇文章      下一篇文章      查看所有文章
加:2021-08-05 17:18:30  更:2021-08-05 17:19:22 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年5日历 -2024/5/17 16:11:41-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码