美文网首页
python编程导论 week 3

python编程导论 week 3

作者: 猪蹄炖粥 | 来源:发表于2018-07-23 22:58 被阅读4次

    数据化类型

    • 元祖

      • an ordered sequence of li items
      • 与list的唯一区别:一旦被创建不可被修改,不可变所以经常用作字典中的键
      • slicing operator:[]
      • 多重赋值
      a, b, c = 'xyz'
      
      t = (5,'program', 1+3j)
      
      # t[1] = 'program'
      print("t[1] = ", t[1])
      
      # t[0:3] = (5, 'program', (1+3j))
      print("t[0:3] = ", t[0:3])
      
      # Generates error
      # Tuples are immutable
      t[0] = 10
      
    • 范围(range)

      • range类型的对象占用的空间与其长度不成正比。因为范围是由起
        始值、结束值和步长定义的,它的存储仅占用很小的一部分空间

      • range(start,stop,step)

      • range(10)[2:6][2]

      • 如果两个范围表示同样的整数序列,那么就返回True

      • #true
         range(0, 7, 2) == range(0, 8, 2)
        
    • list

      • list操作
      L.append(e): 将对象e追加到L的末尾。
      L.count(e): 返回e在L中出现的次数。
      L.insert(i, e): 将对象e插入L中索引值为i的位置。
      L.extend(L1): 将L1中的项目追加到L末尾。
      L.remove(e): 从L中删除第一个出现的e。
      L.index(e): 返回e第一次出现在L中时的索引值。如果e不在L中,则抛出一
      个异常(参见第7章)。
      L.pop(i): 删除并返回L中索引值为i的项目。如果L为空,则抛出一个异常。
      如果i被省略,则i的默认值为-1,删除并返回L中的最后一个元素。
      L.sort(): 升序排列L中的元素。
      L.reverse(): 翻转L中的元素顺序。
      
      • 切片操作克隆
      for e1 in L1[:]
      
      • 列表推导
      • 列表推导式提供了一种简洁的方式,将某种操作应用到序列中的一个值上。它会创建一个新
        列表
      L = [x**2 for x in range(1,7)]
      
    • 高阶函数

      • 函数的参数包含函数
      • map函数 map(fn,[1,2,3])
      • applyToEach applyToEach([1,2,3],fn)
    • 字典dictionary

      • 键值对表示
      • dict中的项目是无序的,不能通过[i]来索引
      • 迭代过程中不指定顺序,返回key

    注:反斜杠:表示下一行是上一行的延续

    理解生成器和迭代器

    • 迭代器
      • 迭代器就是实现了工厂模式的对象,它在你每次你询问要下一个值的时候给你返回
      • 任何实现了__iter__next()(python2中实现next())方法的对象都是迭代器,__iter__返回迭代器自身,__next__返回容器中的下一个值
    #迭代器实现斐波那契数列
    class Fib:
        def __init__(self):
            self.prev = 0
            self.curr = 1
    
        def __iter__(self):
            return self
    
        def __next__(self):
            value = self.curr
            self.curr += self.prev
            self.prev = value
            return value
    
    # f = Fib()
    # list(islice(f, 0, 10))
    #[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
    
    • generator

      • yiled关键字
      • 生成器是一种特殊的迭代器,它的返回值不是通过return而是用yield
      #生成器实现斐波那契数列
      def fib():
          prev, curr = 0, 1
          while True:
              yield curr
              prev, curr = curr, curr + prev
      
      # f = fib()
      # list(islice(f, 0, 10))
      #[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
      
    • 生成器表达式,类似于列表表达式,但返回的是一个生成器对象,而不是列表丢向

       a = (x*x for x in range(10))
       a
      #<generator object <genexpr> at 0x401f08>
      sum(a)
      

    练习 map/reduce 、filter 、 sorted以及匿名函数

    • map(function, iterable)

      • applies Function and return a List
      def calculateSquare(n):
        return n*n
      
      numbers = (1, 2, 3, 4)
      result = map(calculateSquare, numbers)
      # lambda
      result = map(lambda x: x*x, numbers)
      #result [1,4,9,16]
      
      
      num1 = [4, 5, 6]
      num2 = [5, 6, 7]
      
      result = map(lambda n1, n2: n1+n2, num1, num2)
      print(list(result))
      
      #[9, 11, 13]
      
    • reduce

      • reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4)
    def fn(x, y):
        return x * 10 + y
    
     def char2num(s):
         return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[s]
     reduce(fn, map(char2num, '13579'))
    #13579
    
    • sorted

      • sorted(irerable,reverse,key)
      • iterable: sequence (string, tuple, list) or collection (set, dictionary, frozen set) or any iterator
      • Note: A list also has sort() method which performs the same way as sorted(). Only difference being, sort() method doesn't return any value and changes the original list itself.
      def takeSecond(elem):
          return elem[1]
      
      # random list
      random = [(2, 2), (3, 4), (4, 1), (1, 3)]
      
      # sort list with key
      sortedList = sorted(random, key=takeSecond)
      

    • filter

      • filter(function, iterable)

        alphabets = ['a', 'b', 'd', 'e', 'i', 'j', 'o']
        
        # function that filters vowels
        def filterVowels(alphabet):
            vowels = ['a', 'e', 'i', 'o', 'u']
        
            if(alphabet in vowels):
                return True
            else:
                return False
        
        filteredVowels = filter(filterVowels, alphabets)
        
        print('The filtered vowels are:')
        for vowel in filteredVowels:
            print(vowel)
            
        #function is None  
        #we get the elements which are true: 1, a, True and '0' ('0' as a string is also true)   
        randomList = [1, 'a', 0, False, True, '0']
        filteredList = filter(None, randomList)
        
        print('The filtered elements are:')
        for element in filteredList:
            print(element)
        

    视频中的错题总结

    x = [1, 2, [3, 'John', 4], 'Hi'] 
    x[0:1]
    type(x[0:1]) #list
    print(x[0:1]) #[1]
    
    x = range(3, 10)
    type(x) #list
    

    相关文章

      网友评论

          本文标题:python编程导论 week 3

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