zoukankan      html  css  js  c++  java
  • 内置函数

    filter()函数接受一个函数f和一个list,这个函数f的作用是对每个元素进行判断,返回True

    或FaLse,filter()根据判断结果自动过滤不符合条件的元素,返回由符合条件元素组成新list

    列如,要从一个list[1,4,6,7,9,12,17]中删除偶数,保留

    奇数,首先,要编写一个判断奇数的函数:

    def is_odd(x):

    return x% 2==1

    然后,利用filter()过滤掉偶数:

    >>>filter(is_odd,[1,4,6,7,9,12,17])

    结果

    [1,7,9,17]

    利用filter()可以完成很多有用的功能,列如,删除

    None或者空字符串:

    def is_not _empty(s):

    return s and len(s.strip())>0

    >>>filter(is_not _empty,['test',None,'','str','','END'])

    结果:

    ['test','str''END']

    注意:s.strip(rm)删除s字符串中开头头、结尾处的rm

    序列的字符。当rm 为空时,默认删除空白符包括 (

    ' ',' ',' ',''),如下:

    >>>a = '123'

    >>>a.strip()

    '123'

    >>>a=' 123 '

    >>>a.strip()

    '123'

    练习:

    请利用filter()过滤出1~100中平方根是整数的数,

    结尾应该是:

    [1,4,9,16,25,36,49,64,81,100]

    方法:

    import math

    def is_sqr(x):

    return math.aqrt(x) % 1==0

    print filter(is_sqr,range(1,101))

    结果:

    [1,4,9,16,25,36,49,64,81,100]

    map

    python 中的map 函数应用于每一个可迭代的项,返回的是一个

    结果list。如果有其他的可迭代参数传进来,

    map 函数则会把每一个参数都以相应的处理函数

    进行迭代处理。map()函数接到两个参数,一个

    是函数,一个是序列,map将传入的函数依次作用到序列的

    每个元素,并把结果作为新的list返回。

    有一个list ,L=[1,2,3,4,5,6,7,8] 我们要将f(x)=x^2作用于

    这个list上,那么我们可以使用map 函数处理。

    >>>l=[1,2,3,4,]

    >>> def pow2(x)

    >>>map (pow2,l)

    [1,4,9,16]

  • 相关阅读:
    VS2010 自动跳过代码现象
    Reverse Linked List II 【纠结逆序!!!】
    Intersection of Two Linked Lists
    Linked List Cycle II
    Remove Nth Node From End of List 【另一个技巧,指针的指针】
    Swap Nodes in Pairs
    Merge Two Sorted Lists
    Remove Duplicates from Sorted List
    Linked List Cycle
    Dungeon Game
  • 原文地址:https://www.cnblogs.com/djjv/p/7270197.html
Copyright © 2011-2022 走看看