Python 常用内置函数

1. Sorted() 排序函数

作用: 排序(可通过key参数, 函数)

a = [{'name': 'alex', 'age': 76}, {'name': 'bob', 'age': 34}, {'name': 'jan', 'age': 31}, {'name': 'tony', 'age': 43}, {'name': 'ton', 'age': 67}]
b = sorted(a, key=lambda x: x.get('age', 0)) #age进行排序, 无则0
print(b)

执行结果:

2. filter() 过滤函数

作用: 用于过滤序列,过滤掉不符合条件的元素,返回由符合条件元素组成的新列表

该接受两个参数,第一个为函数,第二个为序列,序列的每个元素作为参数传递给函数进行判断,然后返回True和False,最后将返回True的元素放到新列表中。

注意:Python2.7返回列表,Python3.x返回迭代器对象

语法:

filter(function, iterable)

参数:

function -- 判断函数

iterable  -- 可迭代对象

实例:

def test(num):
    return True if num % 2 else False

# function函数返回True和FALSE
newlist = filter(test, [i for i in range(10)]) # 迭代器对象

print(newlist.__iter__())
print(newlist.__next__())
print(newlist.__next__())
print(newlist.__next__())
print(newlist.__next__())

for v in newlist:
    print(v)

执行结果:

3. map() 映射函数

作用: map可以根据提供的函数对指定序列做映射, 它接受一个函数和一个list, 并通过把函数function作用在list上的每个元素, 然后返回一个新的list, map函数的传参也可以是多个, 注意这个函数一定要有返回值

def map_test(num1, num2):
    return num1 * num2


list_test1 = [2, 5, 1, 3, 6, 32]
list_test2 = [5, 2, 4, 6, 3, 1]
res = map(map_test, list_test1, list_test2)
print(res, list(res))

执行结果:

4. enumerate()

dict_test = [{'name': 'alex', 'age': 76}, {'name': 'bob', 'age': 34}, {'name': 'jan', 'age': 31}, {'name': 'tony', 'age': 43}, {'name': 'ton', 'age': 67}]
for index, val in enumerate(dict_test):
    print(index, val) #索引, 值 

执行结果:

5. zip()

作用: zip函数接受任意多个(包括0个和1个)序列作为参数, 返回一个tuple列表

x = [1, 2, 3]
y = [4, 5, 6]
z = [7, 8, 9]
xyz = zip(x, y, z)
print(xyz, list(xyz))

name_list = ['alex', 'bob', 'jan', 'tony']
age_list = [2, 43, 54, 5, 4]
res = zip(name_list, age_list)
print(dict(res))

执行结果:

原文地址:https://www.cnblogs.com/yunxintryyoubest/p/14416088.html