美文网首页
python的内置函数

python的内置函数

作者: 风___________ | 来源:发表于2018-04-09 11:43 被阅读1次

列表/字典/元组推导式 比下面的两个函数更优雅~

Map会将一个函数映射到一个输入列表的所有元素上(lambdas :匿名函数)
语法:map(方法,数组)
items = [1, 2, 3, 4, 5]
squared = []
for i in items:
    squared.append(i**2)
items = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, items))

稍复杂的使用:(方法也是对象,funcs:方法数组)

def multiply(x):
        return (x*x)
def add(x):
        return (x+x)

funcs = [multiply, add]
for i in range(5):
    value = map(lambda x: x(i), funcs)
    print(list(value))
    #        上面print时,加了list转换,是为了python2/3的兼容性
    #        在python2中map直接返回列表,但在python3中返回迭代器
    #        因此为了兼容python3, 需要list转换一下
# Output:
# [0, 0]
# [1, 2]
# [4, 4]
# [9, 6]
# [16, 8]

filter过滤列表中的元素

number_list = range(-5, 5)
less_than_zero = filter(lambda x: x < 0, number_list)
print(list(less_than_zero))  

Reduce对一个列表进行一些计算并返回结果

from functools import reduce
product = reduce( (lambda x, y: x * y), [1, 2, 3, 4] )

# Output: 24

相关文章

网友评论

      本文标题:python的内置函数

      本文链接:https://www.haomeiwen.com/subject/zqabhftx.html