python内置函数:lambda、filter、map、zip以及list中sort的简单使用

lambda的简单使用:

func = lambda a1, a2: a1 + a2

func1 = lambda a3: a3/2

print(func(100, 200)) # 运行结果:300
print(func1(4))       # 运行结果:2.0

不使用lambda时的写法:

def func(a1, a2):
    return a1 + a2


def func1(a1):
    return a1/2


print(func(100, 200))
print(func1(4))

filter过滤函数的用法:

def func1(a):
    if a % 2 == 0:
        return a

#学习中遇到问题没人解答?小编创建了一个Python学习交流群:711312441
func1 = list(filter(func1, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]))
print(func1) # 运行结果:[2, 4, 6, 8, 10]

res = list(filter(lambda x: x % 2 == 0, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]))
print(res) # 运行结果:[2, 4, 6, 8, 10]

zip函数的用法:

def func_zip(n, m):
    return zip(n, m)

# 用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组
title = ["name", "age", "gender"]
info = ["benben", 18, "女"]
res = dict(func_zip(title, info))
print(res)

res = lambda x, y: zip(x, y)
print(dict(res(title, info)))

#运行结果: {'name': 'benben', 'age': 18, 'gender': '女'}

列表中sort方法的使用

test = [
    {"casename": "测试1", "order": 2, "开启": "是"},
    {"casename": "测试2", "order": 1, "开启": "是"},
    {"casename": "测试3", "order": 4, "开启": "否"},
    {"casename": "测试4", "order": 3, "开启": "是"},
]


def filter_fun(ele):
    return ele["开启"] == "是"


res = list(filter(filter_fun, test))
print(res)

res = list(filter(lambda t: t.get("开启") == "是", test))
print(res)


def order_fun(ele):
    return ele["order"]


res.sort(key=order_fun)
print(res)

res.sort(key=lambda x: x["order"], reverse=True)
print(res)

你可能感兴趣的:(python,list,windows)