自学内容网 自学内容网

学习之高阶编程的内置函数

“”"
filter函数:过滤器
参数1:过滤规则函数
参数2:可迭代对象
“”"

def test_filer():
    """
    需求: 获取列表中大于30的数据
    li = [11, 34, 7, 66, 5, 234, 55, 6]
    :return:
    """
    li = [11, 34, 7, 66, 5, 234, 55, 6]

    li1 = [i for i in li if i > 30]
    res1 = filter(lambda x: x > 30, li)
    print(list(res1))
    return li1

“”"
map函数:将函数应用于iterable中的每一项并输出其结果
参数1:处理函数
参数2:可迭代对象
需求:计算列表中所有数据的二次方法
“”"

def test_map():
    li = [11, 34, 7, 66, 5, 234, 55, 6]
    res = [i*i for i in li]
    li1 = map(lambda x: x ** 2, li)
    return list(li1), res

能使用filter与map的基本上都能使用列表推导式

“”"
exec:执行python代码
需求:字符串中的python代码如何执行
“”"

def test_exec():
    """
    动态执行python字符串代码
    :return:
    """
    code = """
a=100
b=200
print(a+b)    
"""
    exec(code)

all 迭代对象内所有的元素为真,返回True,只要有一个为false那返回的就是false

def test_all():
    return all([1, 2, 12])

any 迭代对象内只要有一个元素为真,返回true

def test_any():
    return any([0, 1, 2])

“”"
zip函数:聚合打包
a.返回一个zip对象
b.它是元组的迭代器,其中每个传递的迭代器中的第一项配对在一起,然后每个传递的迭代器中的第二项配对在一起等
c.如果传递的迭代器具有不同的长度,则具有最少项的迭代器决定迭代器的长度
d.如果我们不传递任何参数,zip()返回一个空迭代器
e.如果传递单个可迭代对象,则zip()返回一个元组迭代器,每个元组只有一个元素
“”"

def test_zip():
    s1 = (1, 2, 3, 4, 5)
    s2 = ("hello", "world", "a", "b", "c", "d")
    s3 = (11, 22, 33)
    s4 = (12, 44, 55, 66)
    res = zip(s1, s2)
    val1 = list(res)  # 嵌套二元元组的列表能够转化为字典
    val2 = dict(val1)
    val3 = zip(s1, s2, s3, s4)
    val4 = zip(s1)


def test_zip_dict():
    case1 = [
        ["case_id", "case_title", "url", "data", "except"],
        ["1", "用例1", "http://www.baidu.com", "001", "ok"],
        ["2", "用例2", "http://www.baidu.com", "001", "ok"],
        ["3", "用例3", "http://www.baidu.com", "001", "ok"],
        ["4", "用例4", "http://www.baidu.com", "001", "ok"],
        ["5", "用例5", "http://www.baidu.com", "001", "ok"]
    ]
    head_list = case1[0]
    body_list = case1[1:]
    res = [dict(zip(head_list, case)) for case in body_list]
    return res


if __name__ == '__main__':
    print(test_filer())
    print(test_map())
    test_exec()  # 会直接打印结果,如果加一层print会返回一个None
    print(test_all())
    print(test_any())
    test_zip()
    test_zip_dict()

原文地址:https://blog.csdn.net/qq_42792477/article/details/142851386

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!