1 列表方法
list.append(x) # 添加一个元素x
list.extend(L) # 添加L列表中的所有元素
list.insert(i,x) # 在列表指定位置插入一个元素
list.remove(x) # 删除列表中值为x的元素
list.pop(i) # 删除列表中指定位置的元素并返回元素值
list.clear() # 清空列表
list.index(x) # 返回列表中第一个值为x的元素索引
list.count(x) # 返回列表中x出现的次数
list.sort() # 对列表进行排序
list.reverse() # 返回列表元素的逆序排列
list.copy() # 浅拷贝
1.1 列表用作堆栈
用 append() 添加元素,pop() 取出元素。
stack = [3, 4, 5]
stack.apppend(6)
stack.pop()
1.2 列表用作队列
from collections import deque
queue = deque(["Eric", "John", "Michael"])
queue.append("Terry")
queque.popleft()
1.3 列表推导式
# 普通方法
squares = []
for x in range(10):
squares.append(x**2)
# 列表推导式
squares = list(map(lambda x: x**2, range(10)))
squares = [x**2 for x in range(10)]
一些例子:
>>> vec = [-4, -2, 0, 2, 4]
>>> # create a new list with the values doubled
>>> [x*2 for x in vec]
[-8, -4, 0, 4, 8]
>>> # filter the list to exclude negative numbers
>>> [x for x in vec if x >= 0]
[0, 2, 4]
>>> # apply a function to all the elements
>>> [abs(x) for x in vec]
[4, 2, 0, 2, 4]
>>> # 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)]
[(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]
>>> # the tuple must be parenthesized, otherwise an error is raised
>>> [x, x**2 for x in range(6)]
File "<stdin>", line 1, in ?
[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]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
列表表达式还支持更复杂的表达式和嵌套函数:
from math import pi
[str(round(pi, i)) for i in range(1, 6)]
1.4 嵌套的列表表达式
matrix = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
]
# 交换行与列
[[row[i] for row in matrix] for i in range(4)]
# s使用zip()函数
list(zip(*matrix))
2 del语句
按照索引删除指定的值
>>> a = [-1, 1, 66.25, 333, 333, 1234.5]
>>> del a[0]
>>> a
[1, 66.25, 333, 333, 1234.5]
>>> del a[2:4]
>>> a
[1, 66.25, 1234.5]
>>> del a[:]
>>> a
[]
del 也可以删除整个变量:
>>> del a
3 元组和序列
4 集合
>>> basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
>>> print(basket) # show that duplicates have been removed
{'orange', 'banana', 'pear', 'apple'}
>>> 'orange' in basket # fast membership testing
True
>>> 'crabgrass' in basket
False
>>> # Demonstrate set operations on unique letters from two words
...
>>> a = set('abracadabra')
>>> b = set('alacazam')
>>> a # unique letters in a
{'a', 'r', 'b', 'c', 'd'}
>>> a - b # letters in a but not in b
{'r', 'd', 'b'}
>>> a | b # letters in either a or b
{'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'}
>>> a & b # letters in both a and b
{'a', 'c'}
>>> a ^ b # letters in a or b but not both
{'r', 'd', 'b', 'm', 'z', 'l'}
# 集合推导式
>>> a = {x for x in 'abracadabra' if x not in 'abc'}
>>> a
{'r', 'd'}
5 字典
>>> 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}
>>> list(tel.keys())
['irv', 'guido', 'jack']
>>> sorted(tel.keys())
['guido', 'irv', 'jack']
>>> 'guido' in tel
True
>>> 'jack' not in tel
False
使用dict()构造字典
dict(sape=4139, guido=4127, jack=4908)
dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
使用简直表达式创建字典
{x: x**2 for x in (2, 4, 6)}
6 循环技巧
字典中的关键字和值的遍历可以用 items()
方法
knights = {'gallahad': 'the pure', 'robin': 'the brave'}
for k, v in knights.items():
print(k,v)
序列中遍历索引和相应的值可以用 enumerate()
方法
for i, v in enumerate(['tic', 'tac', 'toe']):
print(i, v)
同时遍历多个序列时,可使用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))
逆序遍历,使用 reversed()
方法
for i reversed(range(1, 10, 2)):
print(i)
7 深入条件控制
>>> string1, string2, string3 = '', 'Trondheim', 'Hammer Dance'
>>> non_null = string1 or string2 or string3
8 比较序列和其他类型
序列对象可以和相同的类型进行比较。
(1, 2, 3) < (1, 2, 4)
[1, 2, 3] < [1, 2, 4]
'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)