10.1 A list is a sequence
Like a string, a list is a sequence of values. In a string, the values are characters; in a list, they can be any type. The values in a list are called elements or sometimes items.
There are several ways to create a new list; the simplest is to enclose the elements in square brackets ([and]):

[10, 20, 30, 40]
['crunchy frog', 'ram bladder', 'lark vomit']

The first example is a list of four integers. The second is a list of three strings. The elements of a list don’t have to be the same type. The following list contains a string, a float, an integer, and (lo!) another list:

['spam', 2.0, 5, [10, 20]]

A list within another list is nested.
A list that contains no elements is called an empty list; you can create one with empty brackets, [].
As you might expect, you can assign list values to variables:

>>> cheeses = ['Cheddar', 'Edam', 'Gouda']
>>> numbers = [17, 123]
>>> empty = []
>>> print cheeses, numbers, empty
['Cheddar', 'Edam', 'Gouda'] [17, 123] []

10.2 Lists are mutable
The syntax for accessing the elements of a list is the same as for accessing the characters of a string — the bracket operator. The expression inside the brackets specifies the index.
Remember that the indices start at 0:

>>> print cheeses[0]
Cheddar

Unlike strings, lists are mutable. When the bracket operator appears on the left side of an assignment, it identifies the element of the list that will be assigned.

>>> numbers = [17, 123]
>>> numbers[1] = 5
>>> print numbers
[17, 5]

The one-eth element of numbers, which used to be 123, is now 5. You can think of a list as a relationship between indices and elements. This relationship is called a mapping; each index “maps to” one of the elements. Figure 10.1 shows the state diagram for cheeses, numbers and empty:
Lists are represented by boxes with the word “list” outside and the elements of the list inside. cheeses refers to a list with three elements indexed 0, 1 and 2. numbers contains two elements; the diagram shows that the value of the second element has been reassigned from 123 to 5. empty refers to a list with no elements.
List indices work the same way as string indices:

  • Any integer expression can be used as an index.
  • If you try to read or write an element that does not exist, you get an IndexError.
  • If an index has a negative value, it counts backward from the end of the list.

The in operator also works on lists.

>>> cheeses = ['Cheddar', 'Edam', 'Gouda']
>>> 'Edam' in cheeses
True
>>> 'Brie' in cheeses
False

10.3 Traversing a list
The most common way to traverse the elements of a list is with a for loop. The syntax is the same as for strings:

for cheese in cheeses:
print cheese

This works well if you only need to read the elements of the list. But if you want to write or update the elements, you need the indices. A common way to do that is to combine the functions range and len:

for i in range(len(numbers)):
numbers[i] = numbers[i] * 2

This loop traverses the list and updates each element. len returns the number of elements in the list. range returns a list of indices from 0 to n-1, where n is the length of the list. Each time through the loop i gets the index of the next element. The assignment statement in the body uses i to read the old value of the element and to assign the new value.
A for loop over an empty list never executes the body:

for x in []:
print 'This never happens.'

Although a list can contain another list, the nested list still counts as a single element. The length of this list is four:

['spam', 1, ['Brie', 'Roquefort', 'Pol le Veq'], [1, 2, 3]]

10.4 List operations
The + operator concatenates lists:

>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> c = a + b
>>> print c
[1, 2, 3, 4, 5, 6]

Similarly, the * operator repeats a list a given number of times:

>>> [0] * 4
[0, 0, 0, 0]
>>> [1, 2, 3] * 3
[1, 2, 3, 1, 2, 3, 1, 2, 3]

The first example repeats [0] four times. The second example repeats the list [1, 2, 3] three times.

10.5 List slices
The slice operator also works on lists:

>>> t = ['a', 'b', 'c', 'd', 'e', 'f']
>>> t[1:3]
['b', 'c']
>>> t[:4]
['a', 'b', 'c', 'd']
>>> t[3:]
['d', 'e', 'f']

If you omit the first index, the slice starts at the beginning. If you omit the second, the slice goes to the end. So if you omit both, the slice is a copy of the whole list.

>>> t[:]
['a', 'b', 'c', 'd', 'e', 'f']

Since lists are mutable, it is often useful to make a copy before performing operations that fold, spindle or mutilate lists.
A slice operator on the left side of an assignment can update multiple elements:

>>> t = ['a', 'b', 'c', 'd', 'e', 'f']
>>> t[1:3] = ['x', 'y']
>>> print t
['a', 'x', 'y', 'd', 'e', 'f']

10.6 List methods
Python provides methods that operate on lists. For example, append adds a new element to the end of a list:

>>> t = ['a', 'b', 'c']
>>> t.append('d')
>>> print t
['a', 'b', 'c', 'd']

extend takes a list as an argument and appends all of the elements:

>>> t1 = ['a', 'b', 'c']
>>> t2 = ['d', 'e']
>>> t1.extend(t2)
>>> print t1
['a', 'b', 'c', 'd', 'e']

This example leaves t2 unmodified.
sort arranges the elements of the list from low to high:

>>> t = ['d', 'c', 'e', 'b', 'a']
>>> t.sort()
>>> print t
['a', 'b', 'c', 'd', 'e']

List methods are all void; they modify the list and return None. If you accidentally write t = t.sort(), you will be disappointed with the result.

10.7 Map, filter and reduce
To add up all the numbers in a list, you can use a loop like this:

def add_all(t):
total = 0
for x in t:
total += x
return total

total is initialized to 0. Each time through the loop, x gets one element from the list. The += operator provides a short way to update a variable. This augmented assignment statement:

total += x

is equivalent to:

total = total + x

As the loop executes, total accumulates the sum of the elements; a variable used this way is sometimes called an accumulator.
Adding up the elements of a list is such a common operation that Python provides it as a built-in function, sum:

>>> t = [1, 2, 3]
>>> sum(t)
6

An operation like this that combines a sequence of elements into a single value is sometimes called reduce.

Sometimes you want to traverse one list while building another. For example, the following function takes a list of strings and returns a new list that contains capitalized strings:

def capitalize_all(t):
res = []
for s in t:
res.append(s.capitalize())
return res

res is initialized with an empty list; each time through the loop, we append the next element. So res is another kind of accumulator.
An operation like capitalize_all is sometimes called a map because it “maps” a function (in this case the method capitalize) onto each of the elements in a sequence.

Another common operation is to select some of the elements from a list and return a sublist. For example, the following function takes a list of strings and returns a list that contains only the uppercase strings:

def only_upper(t):
res = []
for s in t:
if s.isupper():
res.append(s)
return res

isupper is a string method that returns True if the string contains only upper case letters.
An operation like only_upper is called a filter because it selects some of the elements and filters out the others.
Most common list operations can be expressed as a combination of map, filter and reduce. Because these operations are so common, Python provides language features to support them, including the built-in function map and an operator called a “list comprehension.”

10.8 Deleting elements
There are several ways to delete elements from a list. If you know the index of the element you want, you can use pop:

>>> t = ['a', 'b', 'c']
>>> x = t.pop(1)
>>> print t
['a', 'c']
>>> print x
b

pop modifies the list and returns the element that was removed. If you don’t provide an index, it deletes and returns the last element.
If you don’t need the removed value, you can use the del operator:

>>> t = ['a', 'b', 'c']
>>> del t[1]
>>> print t
['a', 'c']

If you know the element you want to remove (but not the index), you can use remove:

>>> t = ['a', 'b', 'c']
>>> t.remove('b')
>>> print t
['a', 'c']

The return value from remove is None.
To remove more than one element, you can use del with a slice index:

>>> t = ['a', 'b', 'c', 'd', 'e', 'f']
>>> del t[1:5]
>>> print t
['a', 'f']

As usual, the slice selects all the elements up to, but not including, the second index.

10.9 Lists and strings
A string is a sequence of characters and a list is a sequence of values, but a list of characters is not the same as a string. To convert from a string to a list of characters, you can use list:

>>> s = 'spam'
>>> t = list(s)
>>> print t
['s', 'p', 'a', 'm']

Because list is the name of a built-in function, you should avoid using it as a variable name. I also avoid l because it looks too much like 1. So that’s why I use t.
The list function breaks a string into individual letters. If you want to break a string into words, you can use the split method:

>>> s = 'pining for the fjords'
>>> t = s.split()
>>> print t
['pining', 'for', 'the', 'fjords']

An optional argument called a delimiter specifies which characters to use as word boundaries. The following example uses a hyphen as a delimiter:

>>> s = 'spam-spam-spam'
>>> delimiter = '-'
>>> s.split(delimiter)
['spam', 'spam', 'spam']

join is the inverse of split. It takes a list of strings and concatenates the elements. join is a string method, so you have to invoke it on the delimiter and pass the list as a parameter:

>>> t = ['pining', 'for', 'the', 'fjords']
>>> delimiter = ' '
>>> delimiter.join(t)
'pining for the fjords'

In this case the delimiter is a space character, so join puts a space between words. To concatenate strings without spaces, you can use the empty string, '', as a delimiter.

10.10 Objects and values
If we execute these assignment statements:

a = 'banana'
b = 'banana'

We know that a and b both refer to a string, but we don’t know whether they refer to the same string. There are two possible states, shown in Figure 10.2.
In one case, a and b refer to two different objects that have the same value. In the second case, they refer to the same object.
To check whether two variables refer to the same object, you can use the is operator.

In this example, Python only created one string object, and both a and b refer to it.
But when you create two lists, you get two objects:

>>> a = [1, 2, 3]
>>> b = [1, 2, 3]
>>> a is b
False

So the state diagram looks like Figure 10.3.
In this case we would say that the two lists are equivalent, because they have the same elements, but not identical, because they are not the same object. If two objects are identical, they are also equivalent, but if they are equivalent, they are not necessarily identical.
Until now, we have been using “object” and “value” interchangeably, but it is more precise to say that an object has a value. If you execute [1,2,3], you get a list object whose value is a sequence of integers. If another list has the same elements, we say it has the same value, but it is not the same object.

10.11 Aliasing
If a refers to an object and you assign b = a, then both variables refer to the same object:

>>> a = [1, 2, 3]
>>> b = a
>>> b is a
True

The state diagram looks like Figure 10.4.
The association of a variable with an object is called a reference. In this example, there are two references to the same object.
An object with more than one reference has more than one name, so we say that the object is aliased.
If the aliased object is mutable, changes made with one alias affect the other:

>>> b[0] = 17
>>> print a
[17, 2, 3]

Although this behavior can be useful, it is error-prone. In general, it is safer to avoid aliasing when you are working with mutable objects.
For immutable objects like strings, aliasing is not as much of a problem. In this example:

a = 'banana'
b = 'banana'

It almost never makes a difference whether a and b refer to the same string or not.

10.12 List arguments
When you pass a list to a function, the function gets a reference to the list. If the function modifies a list parameter, the caller sees the change. For example, delete_head removes the first element from a list:

def delete_head(t):
del t[0]

Here’s how it is used:

>>> letters = ['a', 'b', 'c']
>>> delete_head(letters)
>>> print letters
['b', 'c']

The parameter t and the variable letters are aliases for the same object. The stack diagram looks like Figure 10.5.
Since the list is shared by two frames, I drew it between them.
It is important to distinguish between operations that modify lists and operations that create new lists. For example, the append method modifies a list, but the + operator creates a new list:

>>> t1 = [1, 2]
>>> t2 = t1.append(3)
>>> print t1
[1, 2, 3]
>>> print t2
None
>>> t3 = t1 + [4]
>>> print t3
[1, 2, 3, 4]

This difference is important when you write functions that are supposed to modify lists.
For example, this function does not delete the head of a list:

def bad_delete_head(t):
t = t[1:] # WRONG!

The slice operator creates a new list and the assignment makes t refer to it, but none of that has any effect on the list that was passed as an argument.
An alternative is to write a function that creates and returns a new list. For example, tail returns all but the first element of a list:

def tail(t):
return t[1:]

This function leaves the original list unmodified. Here’s how it is used:

>>> letters = ['a', 'b', 'c']
>>> rest = tail(letters)
>>> print rest
['b', 'c']

[全文摘自"Think Python"]

Think Python - Chapter 10 - Lists的更多相关文章

  1. 快速入门:十分钟学会PythonTutorial - Learn Python in 10 minutes

    This tutorial is available as a short ebook. The e-book features extra content from follow-up posts ...

  2. <Web Scraping with Python>:Chapter 1 & 2

    <Web Scraping with Python> Chapter 1 & 2: Your First Web Scraper & Advanced HTML Parsi ...

  3. 十. Python基础(10)--装饰器

    十. Python基础(10)--装饰器 1 ● 装饰器 A decorator is a function that take a function as an argument and retur ...

  4. 『Python基础-10』字典

    # 『Python基础-10』字典 目录: 1.字典基本概念 2.字典键(key)的特性 3.字典的创建 4-7.字典的增删改查 8.遍历字典 1. 字典的基本概念 字典一种key - value 的 ...

  5. python进阶10 MySQL补充 编码、别名、视图、数据库修改

    python进阶10 MySQL补充    编码.别名.视图.数据库修改 一.编码问题 #MySQL级别编码 #修改位置: /etc/mysql/mysql.conf.d/mysqld.cnf def ...

  6. 零元学Expression Blend 4 - Chapter 10 用实例了解布局容器系列-「StackPanel」

    原文:零元学Expression Blend 4 - Chapter 10 用实例了解布局容器系列-「StackPanel」 本系列将教大家以实做案例认识Blend 4 的布局容器,此章介绍的布局容器 ...

  7. python学习10—迭代器、三元表达式与生成器

    python学习10—迭代器.三元表达式与生成器 1. 迭代器协议 定义:对象必须提供一个next方法,执行该方法或者返回迭代中的下一项,或者返回一个StopIteration异常,以终止迭代(只能往 ...

  8. Python 3.10 版本采纳了首个 PEP,中文翻译即将推出

    现在距离 Python 3.9.0 的最终版本还有 3 个月,官方公布的时间线是: 3.9.0 beta 4: Monday, 2020-06-29 3.9.0 beta 5: Monday, 202 ...

  9. Python 3.10 的首个 PEP 诞生,内置类型 zip() 迎来新特性

    译者前言:相信凡是用过 zip() 内置函数的人,都会赞同它很有用,但是,它的最大问题是可能会产生出非预期的结果.PEP-618 提出给它增加一个参数,可以有效地解决大家的痛点. 这是 Python ...

随机推荐

  1. jsp标签之<%%>和<%!%>

    <%! %>中声明的是全局变量,不过写前面最好<% %>中声明的是局部变量.<%=%>一般表达式,输出某一变量的值.例如:<%! String totalSt ...

  2. 两天以来对plsqldev操作的记忆

    frist,开机后,打开服务,打开服务,打开服务(重要的事情说三遍). and then, 打开plsqldev,输入TEST账户而不是SYS账户,否则你会被许多未接触到的内容淹没你刚刚创建好的表. ...

  3. iScroll 优化

    iScroll 它比较好的解决了移动互联网 web app 滚动支持问题以及点击事件缓慢的问题,经过简单配置即可让 web app 像原生 app 一样流畅,甚至都不需要改变原来的编码方式,目前它几乎 ...

  4. 关于Linux下C编译错误(警告)cast from 'void*' to 'int' loses precision

    char *ptr; //此后省略部分代码 ) //出错地方 那句话的意思是从 void* 到 int 的转换丢失精度,相信看到解释有些人就明白了, 此问题只会出现在X64位的Linux上,因为在64 ...

  5. WCF中常见的几种Host,承载WCF服务的方法

    1:写在前面 我们都知道WCF在运行的时候必须自己提供宿主来承载服务.WCF 本身没有附带宿主,而是提供了一个 ServiceHost 的类,该类允许您在自己的应用程序中host WCF 服务.然后调 ...

  6. 创建一个ROS msg

    1. msg •msg:msg文件是简单的文本文件,用于描述ROS中消息(消息的各个参数项).用于为不同的编程语言生成有关消息的源代码. •srv:描述服务的文件,由两部分组成:请求和反馈: msg文 ...

  7. Java中Scanner的用法

    转载自: http://blog.csdn.net/pkbilly/article/details/3068912 Scanner是SDK1.5新增的一个类,可是使用该类创建一个对象.Scanner ...

  8. Android 查看webview里面的图片

    今天介绍一下怎么查看WebView里面的图片,首先要设置WebView能够支持JavaScript,然后实现JavaScript的监听接口: mWebView.getSettings().setJav ...

  9. ODI中显示us7ascii字符集的测试

    安装oracle DB时,选择的字符集:美国.英语.US7ASCII. 在不设置nls_lang的情况,插入中文,成功,但存进去的是乱码,select看到也是??(无论后面再怎么设置nls_lang) ...

  10. SQL Server CONVERT() 函数(转)

    定义和用法 CONVERT() 函数是把日期转换为新数据类型的通用函数. CONVERT() 函数可以用不同的格式显示日期/时间数据. 语法 CONVERT(data_type(length),dat ...