Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1753588
  • 博文数量: 335
  • 博客积分: 4690
  • 博客等级: 上校
  • 技术积分: 4341
  • 用 户 组: 普通用户
  • 注册时间: 2010-05-08 21:38
个人简介

无聊之人--除了技术,还是技术,你懂得

文章分类

全部博文(335)

文章存档

2016年(29)

2015年(18)

2014年(7)

2013年(86)

2012年(90)

2011年(105)

分类: Python/Ruby

2011-06-14 00:14:00

3.2. Introducing Lists

Lists are Python's workhorse datatype. If your only experience with lists is arrays in Visual Basic or (God forbid) the datastore in Powerbuilder, brace yourself for Python lists.

列表是Python的主要数据类型。如果你只有VB数组的使用经验或是万恶的Powerbuilder的数据存储的使用经验,那你就拥抱Python的列表吧。

Note

 

A list in Python is like an array in Perl. In Perl, variables that store arrays always start with the @ character; in Python, variables can be named anything, andPython keeps track of the datatype internally.

Python中的列表,同Perl中的数组类似。在Perl中,存储数组的变量以@开始;在Python中,变量名可以为任意名称,而且python会一直记住这种数据类型。

 

 

Note

 

A list in Python is much more than an array in Java (although it can be used as one if that's really all you want out of life). A better analogy would be to theArrayList class, which can hold arbitrary objects and can expand dynamically as new items are added.

Python中的链表的作用要比java中的数组功能强大(如果你实在需要,你可以把它当做数组来用)。一个更恰当的类比应该是数组列表类,它能容纳任意对象并在需要的时候动态扩展。

 

3.2.1. Defining Lists

定义列表

Example 3.6. Defining a List

3.6 定义一个列表

  1. >>> li = ["a", "b", "mpilgrim", "z", "example"]
  2. >>> li
  3. ['a', 'b', 'mpilgrim', 'z', 'example']
  4. >>> li[0]
  5. 'a'
  6. >>> li[4]
  7. 'example'

1

First, you define a list of five elements. Note that they retain their original order. This is not an accident. A list is an ordered set of elements enclosed in square brackets.

首先,你定义了一个含有5个元素的列表。需要主要的注意的是,列表仍然保持这些元素的最初顺序。这不是偶然的。列表是用大括号封装起来的有序元素的集合。

2

A list can be used like a zero-based array. The first element of any non-empty list is always li[0].

列表可以用作按0开始索引的数组。任意非空列表的第一元素总是li[0].

3

The last element of this five-element list is li[4], because lists are always zero-based.

含有5个元素列表的最后一个元素总是li[4],因为列表总是从0开始索引的。

Example 3.7. Negative List Indices

反向索引

  1. >>> li
  2. ['a', 'b', 'mpilgrim', 'z', 'example']
  3. >>> li[-1]
  4. 'example'
  5. >>> li[-3]
  6. 'mpilgrim'

1

A negative index accesses elements from the end of the list counting backwards. The last element of any non-empty list is always li[-1].

反向索引从列表的末尾反向计数来访问元素。任意非空列表的最后一个元素总是li[-1].

2

If the negative index is confusing to you, think of it this way: li[-n] == li[len(li) - n]. So in this list, li[-3] == li[5 - 3] == li[2].

如果你对反向索引感到迷惑,可以按如下的方式来理解:

Li[-n] == li[len[i]-n].在上面的列表中,li[-3] == li[5-3]==li[2].

Example 3.8. Slicing a List

列表切片

  1. >>> li
  2. ['a', 'b', 'mpilgrim', 'z', 'example']
  3. >>> li[1:3]
  4. ['b', 'mpilgrim']
  5. >>> li[1:-1]
  6. ['b', 'mpilgrim', 'z']
  7. >>> li[0:3]
  8. ['a', 'b', 'mpilgrim']

1

You can get a subset of a list, called a “slice”, by specifying two indices. The return value is a new list containing all the elements of the list, in order, starting with the first slice index (in this case li[1]), up to but not including the second slice index (in this case li[3]).

你可以取得列表的一个子集,称之为“切片“,通过两个索引值来确定。返回值是一个新的列表,该列表为所有满足如下条件元素的有序集合:元素从第一个切片索引所引用的元素开始(本例中为li[1],到第二个切片索引元素(不包含本元素)结束。

2

Slicing works if one or both of the slice indices is negative. If it helps, you can think of it this way: reading the list from left to right, the first slice index specifies the first element you want, and the second slice index specifies the first element you don't want. The return value is everything in between.

切片索引值一个为负或者都为负的情况仍可以正常工作。这种索引方式如果对你有帮助,你可以这样理解:从左至右访问列表的元素,第一个切片索引说明了你想要的元素,第二个切片索引值则是你不想要的元素。

3

Lists are zero-based, so li[0:3] returns the first three elements of the list, starting at li[0], up to but not including li[3].

列表是从0开始索引的,所以li[0:3]返回了前列表的前三个元素:从元素li[0]开始,到Li[3]结束但是不包括元素Li[3].

Example 3.9. Slicing Shorthand

3.9 切片技巧

  1. >>> li
  2. ['a', 'b', 'mpilgrim', 'z', 'example']
  3. >>> li[:3]
  4. ['a', 'b', 'mpilgrim']
  5. >>> li[3:]
  6. ['z', 'example']
  7. >>> li[:]
  8. ['a', 'b', 'mpilgrim', 'z', 'example']

1

If the left slice index is 0, you can leave it out, and 0 is implied. So li[:3] is the same as li[0:3] from Example 3.8, “Slicing a List”.

如果左边的切片索引为0,你可以省略而且0也是默认值。因此li[:3]同例3.8li[0:3]效果是一样的

2

Similarly, if the right slice index is the length of the list, you can leave it out. So li[3:] is the same as li[3:5], because this list has five elements.

类似的,如果右边的切边索引值为列表的长度,你同样可以省略。因此Li[3:]li[3:5]是一样的,因为该列表包括5个元素。

3

Note the symmetry here. In this five-element list, li[:3] returns the first 3 elements, and li[3:] returns the last two elements. In fact, li[:n] will always return the first nelements, and li[n:] will return the rest, regardless of the length of the list.

注意到这儿是对称的。在含有5个元素的列表中,li[:3]返回包含前三个元素的列表。Li[3]返回最后两个元素。事实上,li[:n]返回包含前n个元素的列表而Li[n:]返回剩下的元素的列表,不论列表的长度有多长。

4

If both slice indices are left out, all elements of the list are included. But this is not the same as the original li list; it is a new list that happens to have all the same elements. li[:] is shorthand for making a complete copy of a list.

如果两个索引值同时省略,那么就包括所有的元素。但是返回的列表不同于原来的列表,它们是两个不同的对象,刚好拥有相同的元素而已。 li[:]是完整复制一个列表的速记方法

3.2.2. Adding Elements to Lists

向列表添加元素

Example 3.10. Adding Elements to a List

3.10 向列表添加元素

  1. >>> li
  2. ['a', 'b', 'mpilgrim', 'z', 'example']
  3. >>> li.append("new")
  4. >>> li
  5. ['a', 'b', 'mpilgrim', 'z', 'example', 'new']
  6. >>> li.insert(2, "new")
  7. >>> li
  8. ['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new']
  9. >>> li.extend(["two", "elements"])
  10. >>> li
  11. ['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new', 'two', 'elements']

1

append adds a single element to the end of the list.

Append 将一个元素添加到列表尾部。

2

insert inserts a single element into a list. The numeric argument is the index of the first element that gets bumped out of position. Note that list elements do not need to be unique; there are now two separate elements with the value 'new'li[2] and li[6].

Insert 将一个元素插入到列表中。整型参数是第一个需要移动的元素的索引值。需要注意的是,列表的元素不必唯一,列表中的两个独立元素li[2]Li[6]的值相同,都为’new’.

3

extend concatenates lists. Note that you do not call extend with multiple arguments; you call it with one argument, a list. In this case, that list has two elements.

Extend 连接两个列表。值得注意的是,不能使用多个列表参数来调用extend, 只需要一个参数,类型为列表。在上述情况下,该列表包含有两个元素。

Example 3.11. The Difference between extend and append

3.11 extend append的比较

  1. >>> li = ['a', 'b', 'c']
  2. >>> li.extend(['d', 'e', 'f'])
  3. >>> li
  4. ['a', 'b', 'c', 'd', 'e', 'f']
  5. >>> len(li)
  6. 6
  7. >>> li[-1]
  8. 'f'
  9. >>> li = ['a', 'b', 'c']
  10. >>> li.append(['d', 'e', 'f'])
  11. >>> li
  12. ['a', 'b', 'c', ['d', 'e', 'f']]
  13. >>> len(li)
  14. 4
  15. >>> li[-1]
  16. ['d', 'e', 'f']

1

Lists have two methods, extend and append, that look like they do the same thing, but are in fact completely different. extend takes a single argument, which is always a list, and adds each of the elements of that list to the original list.

列表拥有两个方法,extendappend。它们看起来做的事情是相同的,但是确实完全不同的。Extend需要一个单独的参数,类型为列表类型,它把该列表的每一个元素都添加到原列表上。

2

Here you started with a list of three elements ('a''b', and 'c'), and you extended the list with a list of another three elements ('d''e', and 'f'), so you now have a list of six elements.

列表包含三个元素(’a’,’b’,’c’),然后是使用一个含三个元素的列表(’d’,’e’,’f’)来扩展该列表,这时你的列表就包含了六个元素。

3

On the other hand, append takes one argument, which can be any data type, and simply adds it to the end of the list. Here, you're calling the append method with a single argument, which is a list of three elements.

另一方面,append也 需要一个参数,任意数据类型都可以,该方法只是简单的将该参数添加到列表的尾部。这里,正在使用包含三个元素的一个列表作为参数来调用append方法。

4

Now the original list, which started as a list of three elements, contains four elements. Why four? Because the last element that you just appended is itself a list. Lists can contain any type of data, including other lists. That may be what you want, or maybe not. Don't use append if you mean extend.

现在最初的列表,开始的时候包含有三个元素,现在具有4个元素。为什么包含4个元素呢?这是因为你刚刚添加的最后一个元素本身也是一个列表。列表可以包含任意的数据类型,可以包含其它列表。这可能正是你想要的,也可能不是。如果你想扩展(extend)列表,那就不要使用append

3.2.3. Searching Lists

搜索列表

Example 3.12. Searching a List

3.12 搜索列表

  1. >>> li
  2. ['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new', 'two', 'elements']
  3. >>> li.index("example")
  4. 5
  5. >>> li.index("new")
  6. 2
  7. >>> li.index("c")
  8. Traceback (innermost last):
  9.   File "", line 1, in ?
  10. ValueError: list.index(x): x not in list
  11. >>> "c" in li
  12. False

1

index finds the first occurrence of a value in the list and returns the index.

Index 查找值在列表第一次出现的位置,并作为索引值返回。

 

2

index finds the first occurrence of a value in the list. In this case, 'new' occurs twice in the list, in li[2] and li[6], but index will return only the first index, 2.’

Index 查找 first第一次出显的位置。在本例中,’new’出现了两次,分别为li[2]li[6],但是index仅返回第一次的索引值,2.

 

3

If the value is not found in the list, Python raises an exception. This is notably different from most languages, which will return some invalid index. While this may seem annoying, it is a good thing, because it means your program will crash at the source of the problem, rather than later on when you try to use the invalid index.

如果在列表中查不到值,Python将抛出异常。这同其它大多数的语言都是不同的,其它语言通常会返回一个非法值。虽然这看起来可能会让你不高兴,但这是件好事情,这是因为如果你的源代码如果有问题,这意味着你的程序可能回崩溃,而不是稍后让你尝试使用该非法索引值。

 

4

To test whether a value is in the list, use in, which returns True if the value is found or False if it is not.

为了测试列表是否包含一个值,可以使用in,如果在列表中发现该值则返回真,否则返回假。

 

 

Note

 

 

Before version 2.2.1, Python had no separate boolean datatype. To compensate for this, Python accepted almost anything in a boolean context (like an ifstatement), according to the following rules:

  • 0 is false; all other numbers are true.
  • An empty string ("") is false, all other strings are true.
  • An empty list ([]) is false; all other lists are true.
  • An empty tuple (()) is false; all other tuples are true.
  • An empty dictionary ({}) is false; all other dictionaries are true.

These rules still apply in Python 2.2.1 and beyond, but now you can also use an actual boolean, which has a value of True or False. Note the capitalization; these values, like everything else in Python, are case-sensitive.

在版本2.2.1以前,Python没有单独的布尔数据类型。为了弥补这点,Python几乎接受布尔上下文里面的所有表达式值(如if语句),根据下面的规则:

0 为假,所有其他整数为真;

空字符串““为假,非空字符串为真;

孔列表为假,非空列表为真;

空不变列表为假,非空不变列表为真;

空字典为假,非空字典为真;

这些规则仍然使用与2.2.1以及以后版本,但是现在你还是可以使用实际为真或为假的布尔类型变量注意大写字母,这些值,同Python中的其它对象一样,都死大小写敏感的。

 

 

3.2.4. Deleting List Elements

删除列表元素

Example 3.13. Removing Elements from a List

3.13 从列表中移除一个元素

  1. >>> li
  2. ['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new', 'two', 'elements']
  3. >>> li.remove("z")
  4. >>> li
  5. ['a', 'b', 'new', 'mpilgrim', 'example', 'new', 'two', 'elements']
  6. >>> li.remove("new")
  7. >>> li
  8. ['a', 'b', 'mpilgrim', 'example', 'new', 'two', 'elements']
  9. >>> li.remove("c")
  10. Traceback (innermost last):
  11.   File "", line 1, in ?
  12. ValueError: list.remove(x): x not in list
  13. >>> li.pop()
  14. 'elements'
  15. >>> li
  16. ['a', 'b', 'mpilgrim', 'example', 'new', 'two']

1

remove removes the first occurrence of a value from a list.

Remove  移除列表中第一次出现的参数值

2

remove removes only the first occurrence of a value. In this case, 'new' appeared twice in the list, but li.remove("new") removed only the first occurrence.

Remove remove仅仅移除列表中第一次出现的值。在本例中,’new’在列表中出现了两次,但是li.remove(“new”)仅移除了第一次出现的’new”.

3

If the value is not found in the list, Python raises an exception. This mirrors the behavior of the index method.

如果被移除的值在列表中不存在,Python将抛出异常,这同index方法的行为是类似的。

4

pop is an interesting beast. It does two things: it removes the last element of the list, and it returns the value that it removed. Note that this is different from li[-1], which returns a value but does not change the list, and different from li.remove(value), which changes the list but does not return a value.

Pop 是一个很有趣的方法。它做了两件事:首先移除列表的最后一个元素,然后返回被移除元素。这同Li[-1]是不同的,li[-1]仅返回最后一个元素,但是并不从列表中把该元素移除,并不改变列表,同Li.remove(value)也不同,li.remove(value)仅改变列表,但是并不返回值。

3.2.5. Using List Operators

使用列表操作符

Example 3.14. List Operators

3.14 列表操作符

  1. >>> li = ['a', 'b', 'mpilgrim']
  2. >>> li = li + ['example', 'new']
  3. >>> li
  4. ['a', 'b', 'mpilgrim', 'example', 'new']
  5. >>> li += ['two']
  6. >>> li
  7. ['a', 'b', 'mpilgrim', 'example', 'new', 'two']
  8. >>> li = [1, 2] * 3
  9. >>> li
  10. [1, 2, 1, 2, 1, 2]

1

Lists can also be concatenated with the + operator. list = list + otherlist has the same result as list.extend(otherlist). But the + operator returns a new (concatenated) list as a value, whereas extend only alters an existing list. This means that extend is faster, especially for large lists.

列表可以用+进行连接。List = list + otherlist list(otherlist)的结果是以一样的。但是+操作符返回了一个新的连接列表作为返回值,而extend仅仅是修改了一个已经存在的列表。这意味着,extend的效率更高,特别是操作大列表。

2

Python supports the += operator. li += ['two'] is equivalent to li.extend(['two']). The += operator works for lists, strings, and integers, and it can be overloaded to work for user-defined classes as well. (More on classes in Chapter 5.)

Python支持 += 运算符。 Li += [‘two’]li.extend([‘two’]的效果是一样的。+= 支持的数据类型有字符串,列表,整数,它同时还可以被重载以支持用户自定义类。

3

The * operator works on lists as a repeater. li = [1, 2] * 3 is equivalent to li = [1, 2] + [1, 2] + [1, 2], which concatenates the three lists into one.

列表中的*操作符的作用就是重复列表。Li=[1,2]*3 li = [1,2] + [1,2] + [1,2] 的效果是一样的,它将三个列表合并成为一个列表

 

阅读(1014) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~