190712-Python备忘

  • Python中没有 x++ 和 x-- 的操作符。

  • Python也有内置的长整型和复杂数字类型

  • Python实现的布尔逻辑,用的是英语,而不是我们习惯的操作符(比如&&和||等)

  • 如果想要在循环体内访问每个元素的指针,可以在in后使用内置的enumerate(枚举)

    list0 = ['cat', 'dog', 'monkey']
    for index, item in enumerate(list0):
           print '#%d: %s' % (index + 1, item)
    
    #OUTPUT:
    "#1: cat"
    "#2: dog"
    "#3: monkey"
    
  • 对于字典的迭代,访问键和对应的值,那就使用字典对象的iteritems方法:

    dict0 = {'person': 2, 'cat': 4, 'spider': 8}
    for animal, legs in dict0.iteritems():
           print 'A %s has %d legs' % (animal, legs)
    
    #OUTPUT:
    "A person has 2 legs"
    "A spider has 8 legs"
    "A cat has 4 legs"
    
  • 列表推导List comprehensions

    nums = [0, 1, 2, 3, 4] 
    squares = [] 
    for x in nums:
           squares.append(x ** 2) print squares   # Prints [0, 1, 4, 9, 16]
    

    使用列表推导,你就可以让代码简化很多:

    nums = [0, 1, 2, 3, 4]
    squares = [x ** 2 for x in nums]
    print squares   # Prints [0, 1, 4, 9, 16]
    
  • 列表推导还可以包含条件:

     nums = [0, 1, 2, 3, 4]
     even_squares = [x ** 2 for x in nums if x % 2 == 0]
     print even_squares  # Prints "[0, 4, 16]"
    
  • 同样也可做字典推导Dictionary comprehensions、集合推导Set comprehensions

    even_num_to_square = {x: x ** 2 for x in nums if x % 2 == 0}
    nums = {int(sqrt(x)) for x in range(30)}
    
  • Numpy生成数组提供的函数full(shape,elem)、zeros、ones、eye、random.random(shape)

      a = np.zeros((2,2))  # Create an array of all zeros
      print a              # Prints "[[ 0.  0.]
                           #          [ 0.  0.]]"
      
      b = np.ones((1,2))   # Create an array of all ones
      print b              # Prints "[[ 1.  1.]]"
      
      c = np.full((2,2), 7) # Create a constant array
      print c               # Prints "[[ 7.  7.]
                            #          [ 7.  7.]]"
      
      d = np.eye(2)        # Create a 2x2 identity matrix
      print d              # Prints "[[ 1.  0.]
                           #          [ 0.  1.]]"
      
      e = np.random.random((2,2)) # Create an array filled with random values
      print e                     # Might print "[[ 0.91940167  0.08143941]
                                  #               [ 0.68744134  0.87236687]]"
    
  • Numpy 访问数组仍可使用切片,访问元素使用方括号下标[i,j]

      [[2 3]
      [6 7]]
      b = a[:2, 1:3]
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值