sorted&filter&map

python里列表的sort和内置的sorted函数,都可以进行排序,列表的sort方法是在原有的列表上进行排序,sorted是会返回一个新的对象

persons = [
    {'name': '小明', 'age': 25},
    {'name': '小红', 'age': 15},
    {'name': '小贾', 'age': 28},
    {'name': '小乙', 'age': 34}
]

def age(d):
    return d['age']

persons.sort(key=lambda x: x['age'], reverse=True)  # 这个会在原列表上进行排序
persons.sort(key=age, reverse=True)  # 这个会在原列表上进行排序
s = sorted(persons, key=lambda x: x['age'])
f = sorted(persons, key=age)

print(s)

 filter过滤函数

persons = ['孙悟空', '猪八戒', '沙和尚', '唐僧']

s = filter(lambda x: x[-1]!='', persons)
print(list(s))

 map映射函数

def fun(x):
    return x ** 2

s = map(fun, [3, 4, 5, 6])
f = map(lambda x, y: x + y, [3, 4, 5, 6], [3, 4, 5, 6])
print(list(s))
print(list(f))
原文地址:https://www.cnblogs.com/blog-rui/p/12015110.html