python 2.7 中文教程-5:数据结构

本章详细讨论一些已学知识,并引入了一些新知识。

列表的详细介绍


列表的所有方法如下:

    list.append(x):附加元素到列表末端,相当于a[len(a):] = [x]。
    list.extend(L):附加列表L的内容到当前列表后面,相当于 a[len(a):] = L 。
    list.insert(i, x):在指定位置i插入x。i表示插入位置,原来的i位置如果有元素则往后移动一个位置,例如 a.insert(0, x)会插入到列表首部,而a.insert(len(a), x)相当于a.append(x)。
    list.remove(x):删除列表中第一个值为x的元素。如果没有就报错。
    list.pop([i]):产出列表指定位置的元素,并将其返回该元素。如果没有指定索引针对最后一个元素。方括号表示i是可选的。
    list.index(x):返回第一个值为x的元素的索引。如果没有则报错。
    list.count(x):返回x在列表中出现的次数。
    list.sort(cmp=None, key=None, reverse=False):就地对链表中的元素进行排序。
    list.reverse():就地反转元素。

实例:
 

>>> a = [66.2533333311234.5]
>>> print a.count(333)a.count(66.25)a.count('x')
2 1 0
>>> a.insert(2, -1)
>>> a.append(333)
>>> a
[66.25333, -133311234.5333]
>>> a.index(333)
1
>>> a.remove(333)
>>> a
[66.25, -133311234.5333]
>>> a.reverse()
>>> a
[3331234.51333, -166.25]
>>> a.sort()
>>> a
[-1166.253333331234.5]
>>> a.pop()
1234.5
>>> a
[-1166.25333333]
把链表当作堆栈使用


堆栈后进先出。进使用append(),出使用pop()。例如:
 

>>> stack = [345]
>>> stack.append(6)
>>> stack.append(7)
>>> stack
[34567]
>>> stack.pop()
7
>>> stack
[3456]
>>> stack.pop()
6
>>> stack.pop()
5
>>> stack
[34]
把列表当作队列使用

列表先进先出。列表头部插入或者删除元素的效率并不高,因为其他相关元素需要移动,建议使用collections.deque。
 

>>> from collections import deque
>>> queue = deque(["Eric""John""Michael"])
>>> queue.append("Terry")           # Terry arrives
>>> queue.append("Graham")          # Graham arrives
>>> queue.popleft()                 # The first to arrive now leaves
'Eric'
>>> queue.popleft()                 # The second to arrive now leaves
'John'
>>> queue                           # Remaining queue in order of arrival
deque(['Michael''Terry''Graham'])
函数式编程工具


对于列表来讲,有三个内置函数非常有用: filter(), map(), 以及reduce()。

filter(function, sequence)返回function(item)为true的子序列。会尽量返回和sequence相同的类型)。sequence是string或者tuple时返回相同类型,其他情况返回list 。实例:返回能被3或者5整除的序列:
 

>>> def f(x): return x % 3 == 0 or x % 5 == 0
... 
>>> filter(f, range(225))
[356910121518202124]

map(function, sequence) 为每个元素调用 function(item),并将返回值组成一个列表返回。例如计算立方:
 

>>> def cube(x): return x*x*x
...
>>> map(cube, range(111))
[1827641252163435127291000]

 

函数需要多个参数,可以传入对应的序列。如果参数和序列数不匹配,则会报错。如果传入的序列长度不匹配,则用None不全。例如:
 

>>> seq = range(8)
>>> def add(x, y): return x+y
...
>>> map(add, seq, seq)
[02468101214]
>>> seq1 = range(8)
>>> seq2 = range(10)
>>> map(add, seq1, seq2)
Traceback (most recent call last):
  File "<stdin>", line 1in <module>
  File "<stdin>", line 1in add
TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'
>>> map(add, seq1, seq, seq2)
Traceback (most recent call last):
  File "<stdin>", line 1in <module>
TypeError: add() takes exactly 2 arguments (3 given)

reduce(function, sequence) 先以序列的前两个元素调用函数function,再以返回值和第三个参数调用,以此类推。比如计算 1 到 10 的整数之和:
 

>>> def add(x,y): return x+y
...
>>> reduce(add, range(111))
55

如果序列中只有一个元素,就返回该元素,如果序列是空的,就报异常TypeError:

>>> reduce(add, [])
Traceback (most recent call last):
  File "<stdin>", line 1in <module>
TypeError: reduce() of empty sequence with no initial value
>>> reduce(add, [3])
3


可以传入第三个参数作为默认值。如果序列是空就返回默认值。
 

>>> def sum(seq):
...     def add(x,y): return x+y
...     return reduce(add, seq, 0)
... 
>>> sum(range(111))
55
>>> sum([])
0

不要像示例这样定义 sum(),内置的 sum(sequence) 函数更好用。

 

列表推导式

列表推导(表达)式可以快捷地创建列表。用于基于列表元素(可以附加条件)创建列表。

传统方式:
 

>>> squares = []
>>> for x in range(10):
...     squares.append(x**2)
...
>>> squares
[0149162536496481]

列表推导:
 

squares = [x**2 for x in range(10)]

等价于 squares = map(lambda x: x**2, range(10)),但可读性更好、更简洁。

列表推导式包含在放括号中,表达式后有for子句,之后可以有零或多个 for 或 if 子句。结果是基于表达式计算出来的列表:

>>> [(x, y) for x in [1,2,3for y in [3,1,4if x != y]
[(13), (14), (23), (21), (24), (31), (34)]

等同于:
 

>>> combs = []
>>> for x in [1,2,3]:
...     for y in [3,1,4]:
...         if x != y:
...             combs.append((x, y))
...
>>> combs
[(13), (14), (23), (21), (24), (31), (34)]

如果想要得到元组 (例如,上例的 (x, y)),必须在表达式要加上括号:

>>> vec = [-4, -2024]
>># create a new list with the values doubled
>>> [x*2 for x in vec]
[-8, -4048]
>># filter the list to exclude negative numbers
>>> [x for x in vec if x >= 0]
[024]
>># apply a function to all the elements
>>> [abs(x) for x in vec]
[42024]
>># call a method on each element
>>> freshfruit = ['  banana''  loganberry ''passion fruit  ']
>>> [weapon.strip() for weapon in freshfruit]
['banana''loganberry''passion fruit']
>># create a list of 2-tuples like (number, square)
>>> [(x, x**2) for x in range(6)]
[(00), (11), (24), (39), (416), (525)]
>># the tuple must be parenthesized, otherwise an error is raised
>>> [x, x**2 for x in range(6)]
  File "<stdin>", line 1in ?
    [x, x**2 for x in range(6)]
               ^
SyntaxError: invalid syntax
>># flatten a list using a listcomp with two 'for'
>>> vec = [[1,2,3], [4,5,6], [7,8,9]]
>>> [num for elem in vec for num in elem]
[123456789]

列表推导式可使用复杂的表达式和嵌套函数:

>>> from math import pi
>>> [str(round(pi, i)for i in range(16)]
['3.1''3.14''3.142''3.1416''3.14159']
嵌套列表推导式

有如下嵌套列表:
 

>>> matrix = [
...     [1234],
...     [5678],
...     [9101112],
... ]

交换行和列:
 

>>> [[row[i] for row in matrix] for i in range(4)]
[[159], [2610], [3711], [4812]]

等同于:

>>> transposed = []
>>> for i in range(4):
...     transposed.append([row[i] for row in matrix])
...
>>> transposed
[[159], [2610], [3711], [4812]]

也等同于:
 

>>> transposed = []
>>> for i in range(4):
...     # the following 3 lines implement the nested listcomp
...     transposed_row = []
...     for row in matrix:
...         transposed_row.append(row[i])
...     transposed.append(transposed_row)
...
>>> transposed
[[159], [2610], [3711], [4812]]

 zip()内置函数更好:
 

>>> list(zip(*matrix))
[(1, 5, 9)(2, 6, 10)(3, 7, 11)(4, 8, 12)]

 

del 语句

del可基于索引而不是值来删除元素。:del 语句。与 pop() 方法不同,它不返回值。del 还可以从列表中删除区间或清空整个列表。例如:
 

>>> a = [-1166.253333331234.5]
>>> del a[0]
>>> a
[166.253333331234.5]
>>> del a[2:4]
>>> a
[166.251234.5]
>>> del a[:]
>>> a
[]

del 也可以删除整个变量:
 

>>> del a

此后再引用a会引发错误。
 

元组和序列

链表和字符串有很多通用的属性,例如索引和切割操作。它们都属于序列类型(参见 Sequence Types — str, unicode, list, tuple, bytearray, buffer, xrange  https://docs.python.org/2/library/stdtypes.html#typesseq)。Python在进化时也可能会加入其它的序列类型。

元组由逗号分隔的值组成:

>>> t = 1234554321'hello!'
>>> t[0]
12345
>>> t
(1234554321'hello!')
>>> # Tuples may be nested:
... u = t, (12345)
>>> u
((1234554321'hello!'), (12345))
>>> # Tuples are immutable:
... t[0] = 88888
Traceback (most recent call last):
  File "<stdin>", line 1in <module>
TypeError: 'tuple' object does not support item assignment
>>> # but they can contain mutable objects:
... v = ([123], [321])
>>> v
([123], [321])

元组在输出时总是有括号的,嵌套元组可以清晰展示。在输入时可以没有括号,清晰起见,建议尽量添加括号。不能给元组的的元素赋值,但可以创建包含可变对象的元组,比如列表。
元组是不可变的,通常用于包含不同类型的元素,并通过解包或索引访问(collections模块中namedtuple中可以通过属性访问)。列表是可变的,元素通常是相同的类型,用于迭代。
空的括号可以创建空元组;要创建一个单元素元组可以在值后面跟一个逗号单元素元组。丑陋,但是有效。例如:

>>> empty = ()
>>> singleton = 'hello',    # <-- note trailing comma
>>> len(empty)
0
>>> len(singleton)
1
>>> singleton
('hello',)
>>> ('hello',)
('hello',)

语句 t = 12345, 54321, 'hello!' 是 元组打包 (tuple packing)的例子:值12345,54321 和 'hello!' 被封装进元组。其逆操作如下:

>>> x, y, z = t

等号右边可以是任何序列,即序列解包。序列解包要求左侧的变量数目与序列的元素个数相同。

 

集合


集合是无序不重复元素的集。基本用法有关系测试和去重。集合还支持 union(联合),intersection(交),difference(差)和 sysmmetric difference(对称差集)等数学运算。
大括号或set()函数可以用来创建集合。注意:想要创建空集合只能使用 set() 而不是 {}。
 

>>> basket = ['apple''orange''apple''pear''orange''banana']
>>> fruit = set(basket)               # create a set without duplicates
>>> fruit
set(['orange''pear''apple''banana'])
>>'orange' in fruit                 # fast membership testing
True
>>'crabgrass' in fruit
False
>># Demonstrate set operations on unique letters from two words
...
>>> a = set('abracadabra')
>>> b = set('alacazam')
>>> a                                  # unique letters in a
set(['a''r''b''c''d'])
>>> a - b                              # letters in a but not in b
set(['r''d''b'])
>>> a | b                              # letters in either a or b
set(['a''c''r''d''b''m''z''l'])
>>> a & b                              # letters in both a and b
set(['a''c'])
>>> a ^ b                              # letters in a or b but not both
set(['r''d''b''m''z''l'])

类似列表推导式,集合也可以使用推导式:
 

>>> a = {x for x in 'abracadabra' if x not in 'abc'}
>>> a
{'r''d'}

 

字典

字典 (参见 Mapping Types — dict )。字典在一些语言中称为联合内存 (associative memories) 或联合数组 (associative arrays)。字典以key为索引,key可以是任意不可变类型,通常为字符串或数值。

可以把字典看做无序的键:值对 (key:value对)集合。{}创建空的字典。key:value的格式,以逗号分割。

字典的主要操作是依据key来读写值。用 del 可以删除key:value对。读不存在的key取值会导致错误。

keys() 返回字典中所有关键字组成的无序列表。使用 in 可以判断成员关系。

这里是使用字典的一个小示例:
 

>>> tel = {'jack': 4098'sape': 4139}
>>> tel['guido'] = 4127
>>> tel
{'sape': 4139'guido': 4127'jack': 4098}
>>> tel['jack']
4098
>>> del tel['sape']
>>> tel['irv'] = 4127
>>> tel
{'guido': 4127'irv': 4127'jack': 4098}
>>> tel.keys()
['guido''irv''jack']
>>'guido' in tel
True

dict() 构造函数可以直接从 key-value 序列中创建字典:
 

>>> dict([('sape'4139), ('guido'4127), ('jack'4098)])
{'sape': 4139'jack': 4098'guido': 4127}

字典推导式可以从任意的键值表达式中创建字典:
 

>>> {x: x**2 for x in (246)}
{2: 4, 4: 16, 6: 36}

如果关键字都是简单的字符串,可通过关键字参数指定 key-value 对:
 

>>> dict(sape=4139, guido=4127, jack=4098)
{'sape': 4139'jack': 4098'guido': 4127}

 

循环技巧

在序列中循环时 enumerate() 函数同时得到索引位置和对应值:

>>> for i, v in enumerate(['tic''tac''toe']):
...     print(i, v)
...
0 tic
1 tac
2 toe

同时循环两个或更多的序列,可以使用 zip() 打包:

>>> questions = ['name''quest''favorite color']
>>> answers = ['lancelot''the holy grail''blue']
>>> for q, a in zip(questions, answers):
...     print 'What is your {0}?  It is {1}.'.format(q, a)
...
What is your name?  It is lancelot.
What is your quest?  It is the holy grail.
What is your favorite color?  It is blue.

需要逆向循环序列的话,调用 reversed() 函数即可:
 

>>> for i in reversed(xrange(1102)):
...     print(i)
...
9
7
5
3
1

使用 sorted() 函数可排序序列,它不改动原序列,而是生成新的已排序的序列:
 

>>> basket = ['apple''orange''apple''pear''orange''banana']
>>> for f in sorted(set(basket)):
...     print f
...
apple
banana
orange
pear

 iteritems()方法可以同时得到键和对应的值:
 

>>> knights = {'gallahad''the pure''robin''the brave'}
>>> for k, v in knights.iteritems():
...     print k, v
...
gallahad the pure
robin the brave

若要在循环时修改迭代的序列,建议先复制。
 

>>> words = ['cat''window''defenestrate']
>>> for w in words[:]:  # Loop over a slice copy of the entire list.
...     if len(w) > 6:
...         words.insert(0, w)
...
>>> words
['defenestrate''cat''window''defenestrate']

 

深入条件控制

while和if语句中使用的条件可以使用比较,也可包含任意的操作。

比较操作符 in 和 not in判断值是否包含在序列。操作符 is 和 is not 比较两个对象是否相同,适用于可变对象。所有的比较操作符具有相同的优先级,低于所有的数值操作符。

比较操作可以串联。例如 a < b == c 判断是否 a 小于 b 并且 b 等于 c 。

比较操作可以通过逻辑操作符 and 和 or 组合,比较的结果可以用 not 来取反。这些操作符的优先级低于比较操作符,其中not 具有最高的优先级,or 优先级最低,所以 A and not B or C 等于 (A and (notB)) or C。

逻辑操作符 and 和 or 也称作短路操作符:执行顺序从左向右,一旦结果确定就停止。例如A and B and C中,如果 A 和 C 为真而 B 为假,不会解析 C。

可以把比较或其它逻辑表达式的返回值赋给变量,例如:

>>> string1, string2, string3 = '''Trondheim''Hammer Dance'
>>> non_null = string1 or string2 or string3
>>> non_null
'Trondheim'

注意Python与C 不同,在表达式内部不能赋值,避免 C 程序中常见的错误:该用==时误用了=操作符。

序列和其它类型比较

序列对象可以与相同类型的其它对象比较。比较基于字典序:首先比较前两个元素,如果不同,就决定了比较的结果;如果相同,就比较后两个元素,依此类推,直到有序列结束。如果两个元素是同样类型的序列,就递归比较。如果两个序列的所有子项都相等则序列相等。如果一个序列是另一个序列的初始子序列,较短的序列就小于另一个。字符串的字典序基于ASCII。

(1, 2, 3)              < (1, 2, 4)
[123]              < [124]
'ABC' < 'C' < 'Pascal' < 'Python'
(1, 2, 3, 4)           < (1, 2, 4)
(1, 2)                 < (1, 2, -1)
(1, 2, 3)             == (1.0, 2.0, 3.0)
(1, 2, ('aa', 'ab'))   < (1, 2, ('abc', 'a')4)
注意可以比较不同类型的对象也是合法的。比较结果是确定的但是比较随意: 基于类型名(Python未来版本中可能发生变化)排序。因此,列表始终小于字符串,字符串总是小于元组,等等。 不同数值类型按照它们的值比较,所以 0 等于 0.0,等等。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值