python 之 內建函數大全,python內建函數大全

來源:互聯網
上載者:User

python 之 內建函數大全,python內建函數大全

一、羅列全部的內建函數

  戳:https://docs.python.org/2/library/functions.html

二、range、xrange(迭代器)

  無論是range()還是xrange()都是Python裡的內建函數。這個兩個內建函數最常用在for迴圈中。例如:

  1. >>> for i in range(5):
  2. ... print i
  3. ... 
  4. 0
  5. 1
  6. 2
  7. 3
  8. 4
  9. >>> for i in xrange(5):
  10. ... print i
  11. ... 
  12. 0
  13. 1
  14. 2
  15. 3
  16. 4
  17. >>>

range()和xrange() 在Python 2裡是兩種不同的實現。但是在Python 3裡,range()這種實現被移除了;
保留了xrange()的實現,且將xrange()重新命名成range()。

首先,我們來看Python 2裡range()。它是一個內建函數,這個函數用於建立整數等差數列。因此它
常被用於for迴圈。下面是range()的官方協助文檔。

  1. Help on built-in function range in module __builtin__:
  2. range(...)
  3. range(stop) -> list of integers
  4. range(start, stop[, step]) -> list of integers
  5. Return a list containing an arithmetic progression of integers.
  6. range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.
  7. When step is given, it specifies the increment (or decrement).
  8. For example, range(4) returns [0, 1, 2, 3]. The end point is omitted!
  9. These are exactly the valid indices for a list of 4 elements.
  10. (END)

從官方協助文檔,我們可以看出下面的特性:
1、內建函數(built-in)
2、接受3個參數分別是start, stop和step(其中start和step是可選的,stop是必需的)
3、如果沒有指定start,預設從0開始(Python都是從0開始的)
4、如果沒有指定step,預設step是1。(step不能是0,如果指定step為0,“ValueError: range() step argument must not be zero”
      將會被拋出。
額外的特性:
1、當step為正數時,start應該小於stop,否則將產生[ ],即空數列。

  1. >>> range(-3)
  2. []
  3. >>> range(5, 1)
  4. []
  5. >>> range(1,1)
  6. []

2、當step為負數時,start應該大於stop,否則將產生[ ],即空數列。
這兩個特性說明range()可以產生遞增和遞減的數列。
下面是range()產生數列的例子:

  1. >>> range(5)
  2. [0, 1, 2, 3, 4]
  3. >>> range(1,8,3)
  4. [1, 4, 7]
  5. >>> range(0, -10)
  6. []
  7. >>> range(0, -10, -2)
  8. [0, -2, -4, -6, -8]
  9. >>>

接下來看看xrange()。 xrange()雖然也是內建函數,但是它被定義成了Python裡一種類型(type),
這種類型就叫xrange。我們從Python 2的interactive shell裡很容易看到這點。

  1. >>> range
  2. <built-in function range>
  3. >>> xrange
  4. <type 'xrange'>
  5. >>>

我們再來看看xragne的官方協助文檔:

  1. Help on class xrange in module __builtin__:
  2. class xrange(object)
  3. | xrange(stop) -> xrange object
  4. | xrange(start, stop[, step]) -> xrange object
  5. |
  6. | Like range(), but instead of returning a list, returns an object that
  7. | generates the numbers in the range on demand. For looping, this is
  8. | slightly faster than range() and more memory efficient.
  9. |
  10. | Methods defined here:
  11. |
  12. | __getattribute__(...)
  13. | x.__getattribute__('name') <==> x.name
  14. |
  15. | __getitem__(...)
  16. | x.__getitem__(y) <==> x[y]
  17. |
  18. | __iter__(...)
  19. | x.__iter__() <==> iter(x)
  20. |
  21. | __len__(...)
  22. | x.__len__() <==> len(x)
  23. |
  24. | __reduce__(...)
  25. |
  26. | __repr__(...)
  27. | x.__repr__() <==> repr(x)
  28. |
  29. | __reversed__(...)
  30. | Returns a reverse iterator.
  31. |
  32. | ----------------------------------------------------------------------
  33. | Data and other attributes defined here:
  34. |
  35. | __new__ =
  36. | T.__new__(S, ...) -> a new object with type S, a subtype of T
  37. (END)

從文檔裡可以看出,xrange和range的參數和用法是相同的。只是xrange()返回的不再是一個數列,而是一個
xrange對象。這個對象可以按需產生參數指定範圍內的數字(即元素)。由於xrange對象是按需產生單個的
元素,而不像range那樣,首先建立整個list。所以,在相同的範圍內,xrange佔用的記憶體空間將更小,xrange
也會更快。實際上,xrange由於是在迴圈內被調用時才會產生元素,因此無論迴圈多少次,只有當前一個元素
佔用了記憶體空間,且每次迴圈佔用的都是相同的單個元素空間。我們可以粗略的認為,相同n個元素的話,range占
用的空間是xrange的n倍。因此,在迴圈很大情況下,xrange的高效率和快速將表現的很明顯。我們可以用timeit
來測試一下range和xrange的執行時間。

  1. >>> timeit.timeit('for i in range(10000000): pass',number=1)
  2. 0.49290895462036133
  3. >>> timeit.timeit('for i in xrange(10000000): pass',number=1)
  4. 0.2595210075378418

在大量迴圈的條件下,可以看到xrange的高效率是很明顯的。

總結一下:
1、range()返回整個list。
2、xrange()返回的是一個xrange object,且這個對象是個iterable。
3、兩者都用與for迴圈。
4、xrange()佔用更少的記憶體空間,因為迴圈時xrange()只產生當前的元素,不像range()一開始就成產生完整的list。
這就是在Python 2裡range和xrange的相同點和區別。

那麼在Python 3裡,我們在前面提到了range()被移除了,xrange()被重新命名成了range()。它們之間有區別嗎?
請看下面的代碼
Python 2的xrange()

  1. Python 2.7.6 (default, Dec 5 2013, 23:54:52) 
  2. [GCC 4.6.3] on linux2
  3. Type "help", "copyright", "credits" or "license" for more information.
  4. >>> x = xrange(5)
  5. >>> x
  6. xrange(5)
  7. >>> x[:]
  8. Traceback (most recent call last):
  9.   File "", line 1, in <module>
  10. TypeError: sequence index must be integer, not 'slice'
  11. >>> x[-1]
  12. 4
  13. >>> list(x)
  14. [0, 1, 2, 3, 4]
  15. >>> dir(x)
  16. ['__class__', '__delattr__', '__doc__', '__format__', '__getattribute__', '__getitem__', '__hash__', '__init__', '__iter__', '__len__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
  17. >>>

Python 3的range()

  1. Python 3.3.4 (default, Feb 23 2014, 23:07:23) 
  2. [GCC 4.6.3] on linux
  3. Type "help", "copyright", "credits" or "license" for more information.
  4. >>> x = range(5)
  5. >>> x
  6. range(0, 5)
  7. >>> x[:]
  8. range(0, 5)
  9. >>> x[:3]
  10. range(0, 3)
  11. >>> list(x)
  12. [0, 1, 2, 3, 4]
  13. >>> x[-1]
  14. 4
  15. >>> dir(x)
  16. ['__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__','__repr__', '__reversed__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'count', 'index', 'start', 'step', 'stop']
  17. >>>

很明顯,range object在Python裡增加了新的attributes,'count', 'index', 'start', 'step', 'stop'
且能支援slicing。Python 3的range()在xrange()的基礎上變得更強大了。

請理解下面這句話:
The advantage of the range type over a regular list or tuple is that a range object will always take the same (small) amount of memory, no matter the size of the range it represents (as it only stores the startstop and step values, calculating individual items and subranges as needed).

到這裡,我們應該比較清楚range和xrange的區別了

三、yield

def fab(max):    n, a, b = 0, 0, 1    while n < max:        yield b        # print b        a, b = b, a + b        n = n + 1c = fab(10)print(c.__next__())  # python 3.x 已經沒有 next()方法print(c.__next__())print(c.__next__())print(c.__next__())# for i in fab(10):#     print(i)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.