Data Structures
数值Numbers
简单的数值计算,计算器功能
运算符
+ - * /
// #保留整数部分
% #取余数
** #power
字符串Strings
- 单引号和双引号,不冲突原则
- 单引号中
\n
在print
时要换行,使用r
前缀避免解释转意字符 -
+
,*
操作
3 * 'un' + 'ium'
=>unununium
'Py' 'thon'
=>Python
#这种操作只能简单连接,不能复合操作('un' * 3) 'ium'
- Strings can be indexed (subscripted)
word = 'Python'
>>> word[0] # character in position 0
'P'
>>> word[5] # character in position 5
'n'
- 能索引就意味着能切片
>>> word[:2] + word[2:]
'Python'
>>> word[:4] + word[4:]
'Python'
- 看一看索引号,可以这样认为:正索引从0开始左闭右开,负索引从-1开始全闭
+---+---+---+---+---+---+
| P | y | t | h | o | n |
+---+---+---+---+---+---+
0 1 2 3 4 5 6
-6 -5 -4 -3 -2 -1
- 不可通过索引改变string的元素,Python strings cannot be changed — they are immutable
-
len()
returns the length of a string
列表Lists
- 通过
[]
定义列表squares = [1, 4, 9, 16, 25]
- 和String一样List也是内置的sequence类型所以能够使用同样的索引和切片方法
- Lists也支持合并
+
操作 - Lists是mutable的,
- 使用赋值
=
操作来改变元素值cubes[3] = 64
或者letters[2:5] = ['C', 'D', 'E']
- 在末尾加入新项
cubes.append(216)
- 同样可以使用
len()
返回长度 - 支持嵌套使用,It is possible to nest lists (create lists containing other lists)。
>>> 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'
- 下面总结一下Lists的操作方法
list.append(x)**:末尾增一项,这一项可以是各种对象。Add an item to the end of the list; equivalent to
a[len(a):] = [x]
list.extend(L)**:先展开所增对象,然后在末尾一一增项,Extend the list by appending all the items in the given list; equivalent to
a[len(a):] = L
list.insert(i, x)**:在i位置插入一项x。Insert an item at a given position. The first argument is the index of the element before which to insert, so
a.insert(0, x)
inserts at the front of the list, anda.insert(len(a), x)
is equivalent toa.append(x)
list.remove(x)**:删除值为x的索引值最小项。Remove the first item from the list whose value is x. It is an error if there is no such item.
list.pop([i])**:删除并返回给定位置i的项,如果使用pop()则是删除最后一项并返回其值。Remove the item at the given position in the list, and return it. If no index is specified, a.pop()removes and returns the last item in the list. (The square brackets around the i in the method signature denote that the parameter is optional, not that you should type square brackets at that position. You will see this notation frequently in the Python Library Reference.)
list.index(x)**:返回值为x的第一项索引号。Return the index in the list of the first item whose value is x. It is an error if there is no such item.
list.count(x)**:返回x出现的次数。Return the number of times x appears in the list.
list.sort(cmp=None, key=None, reverse=False)**: 排序。Sort the items of the list in place (the arguments can be used for sort customization.
list.reverse():倒转Lists。Reverse the elements of the list, in place.
- 通过上面方法的总结,通常以如下几种方式使用List
- Using Lists as Stacks (“last-in, first-out”):
append
andpop
method, - Using Lists as Queues (“first-in, first-out”): using 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 arrivaldeque(['Michael', 'Terry', 'Graham'])
Functional Programming Tools: 函数式编程工具
有三个内置函数在Lists的使用上非常方便:
-
filer(function, sequence)
: 返回一个sequence,返回序列对原序列的筛选,筛选方法是function。返回的序列与原序列类型相同,可以使用这个方法筛选数据。这里作为参数的function定义有一定要求,fucntion要有一个参数,并且其返回值只能是0或1,所以这个函数逻辑性的过滤函数
>>> def f(x): return x % 3 == 0 or x % 5 == 0
...
>>> filter(f, range(2, 25))
[3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24]
-
map(function,sequence,seq...)
: 返回一个sequence,返回序列各个项是function作用到原序列各个项获得的结果。这里的作用函数特点是,参数个数要与map的序列个数一致,并且各个序列的长度要一致。function返回与这些参数相关的值。这是一个典型的映射操作(map)。
- 单序列映射
>>> def cube(x): return x*x*x
...
>>> map(cube, range(1, 11))
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
- 多序列映射
def func2(x,y,z): return x+y*z
a = range(7); b = range(7,14)
dd = map(func2,a,b,a)
//result:[0, 9, 20, 33, 48, 65, 84]
map()的原理可以用下图表示:
-
reduce(function,seq)
: reduce把一个函数作用在一个序列[x1, x2, x3...]
上,这个函数必须接收两个参数,reduce把结果继续和序列的下一个元素做累积计算,其效果就是:reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4)
。注意,funciton的参数只能有两个。
这里列举几个例子体会一下reduce()
的使用:
- 求和
>>> def add(x, y)
:... return x + y
...
>>> reduce(add, [1, 3, 5, 7, 9])
25
- 把序列
[1, 3, 5, 7, 9]
变换成整数13579
def func3(x,y):
return 10*x+y
ff = reduce(func3,[0,1,2,3,4])
print(ff)
#result: 1234
- 把
str
转换为int
def char2num(s): return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[s]
def str2int(s): return reduce(lambda x,y: x*10+y, map(char2num, s))
List Comprehensions列表生成式
- range
>>> range(1, 11)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
- for...in...
>>> L = []
>>> for x in range(1, 11):
... L.append(x * x)
...
>>> L
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
- 列表生成式(一层循环)
>>> [x * x for x in range(1, 11)]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
当然,还可以用lambda
&map
来写
map(lambda x: x*x, range(1,11))
但是,这样表达没有列表生成器简明易读(it’s more concise and readable)
- 列表生成式(两层循环),所得列表长度等于循环次数
>>> [m + n for m in 'ABC' for n in 'XYZ']
['AX', 'AY', 'AZ', 'BX', 'BY', 'BZ', 'CX', 'CY', 'CZ']
- 列表生成器(增加
if
判断)
>>> [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
Tuples and Sequences 元组和序列
A tuple consists of a number of values separated by commas. tuple通常用
()
表示,tuple属于immutable类型的序列,不支持赋值操作,但是它可以嵌套mutable的list类型( however it is possible to create tuples which contain mutable objects, such as lists.).
- tuple packing:
t = 12345, 54321, 'hello!'
- tuple unpacking:
x,y,z = t
- tuple元素为异构的,通过unpack或index方式访问;sequence元素为同构的,通过iterator方式访问
- 两种特殊的tuple
# tuple with zero or one element
>>> empty = ()
>>> singleton = 'hello', # <-- note trailing comma
>>> singleton
('hello',)
- tuple packing and unpacking
t = 12345, 54321, 'hello!' # packing
x, y, z = t # unpacking
- 遍历list, 按索引值和value值显示, enumerate
>>> for i, v in enumerate(['tic', 'tac', 'toe']):
... print(i, v)
- 同时遍历两个list,
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))
Sets 集合
A set is an unordered collection with no duplicate elements.Set objects also support mathematical operations like union, intersection, difference, and symmetric difference.Note: to create an empty set you have to use
set()
, not{}
,创建空set要使用set()
不能用{}
- 由
list
生成set
>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
>>> fruit = set(basket) # create a set without duplicates
>>> fruit
set(['orange', 'pear', 'apple', 'banana'])
- 由
string
生存set
>>> a = set('abracadabra')
>>> b = set('alacazam')
>>> a # unique letters in a
set(['a', 'r', 'b', 'c', 'd'])
- 集合操作
-
a - b
: 差集 in a but not in b -
a | b
: 或集 in either a or b -
a & b
: 并集 in both a and b -
a ^ b
:(a | b) - (a & b)
in a or b but not both
-
- set comprehensions集合生成器
>>> a = {x for x in 'abracadabra' if x not in 'abc'}
>>> a
set(['r', 'd'])
- 添加与删除方法
- add(key)
- remove(key)
Dictionaries字典
- 删除一个元素,
del(dic)
- 列出所有的key,
list(dic)
- 按value排序key,
sorted(dic)
- 判断key是否存在,
key in dic
- 遍历字典
>>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
>>> for k, v in knights.items():
... print(k, v)