zoukankan      html  css  js  c++  java
  • 22-高级特性之内建方法(3)

    filter

    • 定义:传入一个函数fIterable对象I,返回一个Iterator。根据f(I(i))的返回值是True或False来决定是否保留I(i)。起到过滤器的功能

      def is_odd(x):
      return (x%2 == 1)
      L1 = list(filter(is_odd, range(11))) #filter和map类似,返回值都是一个Iterator,是惰性序列{无穷stream},要用list之类的结构解析出来
      print(L1,' ')

      def ridofempty(s):
      return s and s.strip()
      L2 = ['', 'abc', 'cde', ' ', ' abc', 'cde ']
      L3 = list(filter(ridofempty, L2))
      print(L2,' ', L3, ' ')

    • 筛选法选择素数:

      1.构造产生奇数的gererator:从3开始

      def create_odd():
      n = 1
      while True:
      n += 2
      yield n

      2.构造筛选函数

      def is_divisible(n):
      return (lambda x: (x%n > 0)) #过滤掉n的倍数,即x%n==0的数,此时默认x>n; x待会儿用Iterator传入即可

      3.构造筛选素数的函数

      def GetPrime():
      yield 2 #2作为特殊数据直接输出
      it = create_odd() #产生奇数流,3开始
      while True:
      n = next(it) #下一个产生的素数n
      yield n
      it = filter(is_divisible(n), it) #把刚产生的n,的倍数都过滤掉,再次生成"新的it"

      4.调用100以内的is_prime,产生素数

      primes = GetPrime() #当然primes作为Iterator,当然是Iterable,可以用for迭代
      L4 = []
      while True:
      n = next(primes) #Iterator的特点,可以用next逐个取出
      L4.append(n)
      if (n >= 97):
      break
      print(L4,' ')

    • 作业:筛选出回文数

      print(list(range(10)))

      1.构造从0开始的generator

      def create_num():
      n = 0
      while True:
      yield n
      n += 1

      2.构造筛选函数

      逆转一个整数 print(int((str(123)[-1::-1]))) #先把整数变成字符串,再用[]进行颠倒,最后转化成整数

      def is_palindrome(x):
      return (x == int(str(x)[-1::-1])) #x 与其“反数”是否相等,若等为回文

      print(is_palindrome(123))

      3.构造筛选回文数的函数

      def GetPalindrome():
      it = create_num() #创建自然数集合
      it = filter(is_palindrome, it) #对非回文数进行过滤
      while True:
      n = next(it) #逐个取出并返回
      yield n

      4.调用GetPalindrome

      ps = GetPalindrome()

      L5 = []

      while True:

        # n = next(ps)
        # L5.append(n)
        # if (n >= 1000):
            # break
      

      print(L5)

      L5 = []
      for n in GetPalindrome():
      if (n >= 100000):
      break
      L5.append(n)
      print(L5, ' ')

  • 相关阅读:
    030-B+树(三)
    028-B+树(一)
    027-B树(二)
    026-B树(一)
    025-红黑树(六)
    024-红黑树(五)
    023-红黑树(四)
    022-红黑树(三)
    021-红黑树(二)
    020-红黑树(一)
  • 原文地址:https://www.cnblogs.com/LS1314/p/8504483.html
Copyright © 2011-2022 走看看