zoukankan      html  css  js  c++  java
  • Python2.7学习笔记定义函数、filter/map/reduce/lambda

    我把写的代码直接贴在下面了,注释的不是很仔细,主要是为了自己复习时方便查找,并不适合没有接触过python的人看,其实我也是初学者。

    #定义函数
    def my_abs(x):
        if x>=0:
            return x
        else:
            return -x
    #调用函数
    my_abs(-9)
    
    #filter/map/reduce/lambda
    
    #filter(function,sequence):对sequence中的item依次执行function(item),将执行结果为True的item组成一个List/String/Tuple返回。(取决与sequence的类型)
    def f(x):
        return x%2!=0 and x%5!=0
    filter(f,range(1,20))
    
    def f(x):return x!='u'
    filter(f,'uhjonu')
    
    #map(function, sequence) :对sequence中的item依次执行function(item),执行结果组成一个List返回。
    def square(x):return x+x
    map(square,range(1,10))
    map(square,"abcdef")
    #map也支持多个sequence,这就要求function也支持相应数量的参数输入
    def plus(x,y):
        return x+y
    map(plus,range(5),range(5))
    
    #reduce(function, sequence, starting_value):对sequence中的item顺序迭代调用function,如果有starting_value,还可以作为初始值调用
    def plus(x,y):
        return x+y
    reduce(plus,range(1,10))
    reduce(plus,range(1,10),20)
    
    #lambda的用法
    g=lambda x:x*2
    g(8)  

    我把run出来的结果也贴在下面了,可能软件安装时出了一点问题,结果显示不是很好看,但很容易理解。

    def my_abs(x):
    ...     if x>=0:
    ...         return x
    ...     else:
    ...         return -x
    ... 
    >>> my_abs(-9)
    9>>> 
    
    >>> 
    >>> def f(x):
    ...     return x%2!=0 and x%5!=0
    ... 
    >>> filter(f,range(1,20))
    [>>> 1, 3, 7, 9, 11, 13, 17, 19]
    
    >>> def f(x):return x!='u'
    ... 
    >>> filter(f,'uhjonu')
    '>>> hjon'
    
    >>> def square(x):return x+x
    ... 
    >>> map(square,range(1,10))
    [>>> 2, 4, 6, 8, 10, 12, 14, 16, 18]
    map(square,"abcdef")
    [>>> 'aa', 'bb', 'cc', 'dd', 'ee', 'ff']
    def plus(x,y):
    ...     return x+y
    ... 
    >>> map(plus,range(5),range(5))
    [>>> 0, 2, 4, 6, 8]
    
    >>> def plus(x,y):
    ...     return x+y
    ... 
    >>> reduce(plus,range(1,10))
    4>>> 5
    reduce(plus,range(1,10),20)
    6>>> 5
    
    >>> g=lambda x:x*2
    >>> g(8)  
    1>> >6
  • 相关阅读:
    【leetcode】1365. How Many Numbers Are Smaller Than the Current Number
    【leetcode】1363. Largest Multiple of Three
    【leetcode】1362. Closest Divisors
    【leetcode】1361. Validate Binary Tree Nodes
    【leetcode】1360. Number of Days Between Two Dates
    【leetcode】1359. Count All Valid Pickup and Delivery Options
    【leetcode】1357. Apply Discount Every n Orders
    【leetcode】1356. Sort Integers by The Number of 1 Bits
    ISE应用入门的一些问题
    DDR的型号问题
  • 原文地址:https://www.cnblogs.com/llfisher/p/6382012.html
Copyright © 2011-2022 走看看