非正式介紹Python(二)

3.1.3. Lists

Python knows a number of compound data types, used to group together other values. The most versatile is the list, which can be written as a list of comma-separated values (items) between square brackets. Lists might contain items of different types, but usually the items all have the same type.html

Python擁有複合類型。最通用的是列表,用中括號括起來,元素用逗號隔開。列表能夠包含不一樣的類型,但一般一個列表的全部元素類型都應該是同樣的。python

>>> squares = [1, 4, 9, 16, 25]
>>> squares
[1, 4, 9, 16, 25]

Like strings (and all other built-in sequence type), lists can be indexed and sliced:app

相似於字符串類型(全部的其餘內置序列類型),列表支持索引和切片:函數

>>> squares[0]  # indexing returns the item
1
>>> squares[-1]
25
>>> squares[-3:]  # slicing returns a new list
[9, 16, 25]

All slice operations return a new list containing the requested elements. This means that the following slice returns a new (shallow) copy of the list:ui

全部的切片操做都是返回一個新的列表,所以下面的操做就是複製該列表:this

>>> squares[:]
[1, 4, 9, 16, 25]

Lists also support operations like concatenation:spa

列表也支持鏈接操做:code

>>> squares + [36, 49, 64, 81, 100]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

Unlike strings, which are immutable, lists are a mutable type, i.e. it is possible to change their content:htm

不像字符串是不可變量,列表是可變類型,例如:它能夠改變它自己某個元素的值:blog

>>> cubes = [1, 8, 27, 65, 125]  # something's wrong here
>>> 4 ** 3  # the cube of 4 is 64, not 65!
64
>>> cubes[3] = 64  # replace the wrong value
>>> cubes
[1, 8, 27, 64, 125]

Assignment to slices is also possible, and this can even change the size of the list or clear it entirely:

能夠給切片的子列表賦值,這意味着能夠改變列表中的某段子列表,甚至能夠清空整個列表:

>>> letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> letters
['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> # replace some values
>>> letters[2:5] = ['C', 'D', 'E']
>>> letters
['a', 'b', 'C', 'D', 'E', 'f', 'g']
>>> # now remove them
>>> letters[2:5] = []
>>> letters
['a', 'b', 'f', 'g']
>>> # clear the list by replacing all the elements with an empty list
>>> letters[:] = []
>>> letters
[]

The built-in function len() also applies to lists:

內置函數len()一樣適用於列表:

>>> letters = ['a', 'b', 'c', 'd']
>>> len(letters)
4

It is possible to nest lists (create lists containing other lists), for example:

列表能夠嵌套,也就是列表中的元素也能夠是列表:

>>> a = ['a', 'b', 'c']
>>> n = [1, 2, 3]
>>> x = [a, n]
>>> x
[['a', 'b', 'c'], [1, 2, 3]]
>>> x[0]
['a', 'b', 'c']
>>> x[0][1]
'b'

3.2. First Steps Towards Programming

Of course, we can use Python for more complicated tasks than adding two and two together. For instance, we can write an initial sub-sequence of the Fibonacci series as follows:

固然,咱們能夠使用Python來作更復雜的任務,例如兩個數相加,咱們能夠作一個斐波那契數列以下:

>>> # Fibonacci series:
... # the sum of two elements defines the next
... a, b = 0, 1
>>> while b < 10:
...     print(b)
...     a, b = b, a+b
...
1
1
2
3
5
8
相關文章
相關標籤/搜索