標籤:
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.
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:
類似於字串類型(所有的其他內建序列類型),列表支援索引和切片:
>>> squares[0] # indexing returns the item1>>> 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:
所有的切片操作都是返回一個新的列表,因此下面的操作就是複製該列表:
>>> squares[:][1, 4, 9, 16, 25]
Lists also support operations like concatenation:
列表也支援串連操作:
>>> 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:
不像字串是不可變數,列表是可變類型,例如:它可以改變它本身某個元素的值:
>>> 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...112358
非正式介紹Python(二)