zoukankan      html  css  js  c++  java
  • python lambda,map介绍

    摘自http://www.cnblogs.com/evening/archive/2012/03/29/2423554.html

    >>> foo = [2, 18, 9, 22, 17, 24, 8, 12, 27]
    >>>
    >>> print filter(lambda x: x % 3 == 0, foo)    #过滤出能被3整除的数
    [18, 9, 24, 12, 27]
    >>>
    >>> print map(lambda x: x * 2 + 10, foo)    #等效于  print( [x * 2 + 10 for x in foo]  )
    [14, 46, 28, 54, 44, 58, 26, 34, 64]
    >>>
    >>> print reduce(lambda x, y: x + y, foo)
    139

    map(func, seq1[, seq2,…]) 

    Python函数编程中的map()函数是将func作用于seq中的每一个元素,并将所有的调用的结果作为一个list返回。如果func为None,作用同zip()。#zip意思为拉链

    #使用lambda

    >>> print map(lambda x: x % 2, range(7))

    [0, 1, 0, 1, 0, 1, 0]

    当seq多于一个时,map可以并行(注意是并行)地对每个seq执行

    每个seq的同一位置的元素同时传入一个多元的func函数之后,得到一个返回值,并将这个返回值存放在一个列表中

    >>> print map(lambda x , y : x ** y, [2,4,6],[3,2,1])

    [8, 16, 6]

    PS: map无法处理seq长度不一致、对应位置操作数类型不一致的情况,这两种情况都会报类型错误

     

     

  • 相关阅读:
    hdu1003 最大子串和
    cf339d Xenia and Bit Operations
    A + B Problem II
    中国近代史纲要----王洪兵--2016年春季学期----中国海洋大学
    CodeForces 35D Animals
    CodeForces 558D
    Vanya and Brackets
    spfa
    hdu 1217 Arbitrage
    CodeForces 1A Theatre Square
  • 原文地址:https://www.cnblogs.com/gilgamesh-hjb/p/7248390.html
Copyright © 2011-2022 走看看