1. 程式人生 > >Python學習(五):易忘知識點

Python學習(五):易忘知識點

imp and 同時存在 dict filter tools 交集 brush 列表

1、列表比較函數cmp

>>> a = [1,2,3,4]
>>> b = [1,2,3,4,5]
>>> c = [1,2,3,4]
>>> cmp(a,b)
-1
>>> cmp(a,c)
0

2、列表解析,代碼簡化

>>> a
[1, 2, 3, 4]
>>> d = []
>>> for i in a:
...   d.append(i + 2)
... 
>>> d
[3, 4, 5, 6]
>>> e = []
>>> e = [i + 2 for i in a]
>>> e
[3, 4, 5, 6]

3、字典創建

>>> d = dict.fromkeys([‘today‘,‘tomorrow‘],20)
>>> d
{‘tomorrow‘: 20, ‘today‘: 20}

4、集合特殊性

>>> s = {1,2,3,4}
>>> t = {4,3,6}
>>> s
set([1, 2, 3, 4])
>>> t
set([3, 4, 6])
>>> t | s  # 並集
set([1, 2, 3, 4, 6])
>>> t & s  #交集
set([3, 4])
>>> t - s  #差集 在t中不在s中
set([6])
>>> t ^ s  #對稱差集  不在ts同時存在的值
set([1, 2, 6])

5、函數式編程

    ①map
    >>> a
    [1, 2, 3, 4]
    >>> n = map(lambda x:x+2,a)
    >>> n
    [3, 4, 5, 6]
    #註意:在3.x中需要n = list(n)
    ②reduce
    >>>reduce(lambda x,y:x*y, range(1,8))
    #上述命令相當於
    >>> s = 1
    >>> for i in range(1,8):
    ...   s = s * i
    ... 
    >>> s
    5040
    #註意:python3.x 需要from fuctools import reduce
    ③filter
    >>> b = filter(lambda x: x > 5 and x < 8 , range(10))
    >>> b
    [6, 7]

    #上述函數比for和while循環效率高

6、Python2.x使用print()

  from __future___ import print_function

7、Python2.x 除法更改

  >>> from __future__ import division
  >>> 3/2
  1.5
  >>> 3//2
  1

Python學習(五):易忘知識點