1.序列
-
索引(正/负)
序列中所有元素的编号从0开始递增;使用负数索引时,从右开始往左数,-1是最后一个元素的位置;
>>>greeting = 'Hello' >>>greeting[0] 'H' >>>greeting[-1] 'o' >>>'Hello'[1] 'e' >>>fourth = input('Year: ')[3] Year: 2005 >>>fourth '5'
-
切片
基础:如果第一个参数>=第2个参数的后边,则为空序列[ ](numbers[1:1]即numbers的[1, 1)号元素不存在)
>>>tag = '<a href="http://www.python.org">Python web site</a>' >>>tag[9:30] 'http://www.python.org' >>>tag[32:-4] 'Python web site' >>>numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] #即numbers中[3,6)的元素 >>>numbers[3:6] [4, 5, 6] >>>numbers[0:1] [1] >>>numbers[-3:0] [] >>>numbers[-3:] [8, 9, 10] >>>numbers[:3] [1, 2, 3] >>>numbers[:] [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>>numbers [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
带步长(第三个参数是步长)(正/负)
>>>numbers[0:10:1] [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>>numbers[0:10:2] [1, 3, 5, 7, 9] >>>numbers[3:6:3] [4] >>>numbers[::4] [1, 5, 9] >>>numbers[8:3:-1] [9, 8, 7, 6, 5] >>>numbers[10:0:-2] [10, 8, 6, 4, 2] >>>numbers[0:10:-2] [] >>>numbers[::-2] [10, 8, 6, 4, 2] >>>numbers[5::-2] [6, 4, 2] >>>numbers[:5:-2] [10, 8]
-
序列相加
>>>a = [1, 2, 3] >>>b = [4, 5, 6] >>>a + b [1, 2, 3, 4, 5, 6] >>>a.extend(b) >>>a [1, 2, 3, 4, 5, 6] >>>'Hello, ' + 'world!' 'Hello, world!' >>>[1, 2, 3] + 'world!' Traceback (most recent call last): File "<input>", line 1, in <module> TypeError: can only concatenate list (not "str") to list
注意序列跨行相加时注意使用符号“\”,例如
a = [1, 2] \ + [3, 4]
-
序列乘法
>>>'python' * 5 'pythonpythonpythonpythonpython' >>>[42]*10 [42, 42, 42, 42, 42, 42, 42, 42, 42, 42] >>>[None]*10 [None, None, None, None, None, None, None, None, None, None]
-
成员资格
>>>permissions = 'rw' >>>'w' in permissions True >>>'x' in permissions False >>>users = ['mlh', 'foo', 'bar'] >>>input('Enter your user name: ') in users Enter your user name: >? mlh True >>>subject = '$$$ Get rich now!!! $$$' >>>'$$$' in subject True
-
长度、最大值和最小值
>>>numbers = [100, 34, 678] >>>len(numbers) 3 >>>max(numbers) 678 >>>min(numbers) 34 >>>max(2, 3) 3 >>>min(9, 3, 2, 5) 2
2.列表
-
删除
del参数为索引,remove参数为值
>>>names = ['Alice', 'Beth', 'Cecil', 'Dee-Dee', 'Earl'] >>>del names[2] >>>names ['Alice', 'Beth', 'Dee-Dee', 'Earl'] >>>del names[1:3] >>>names ['Alice', 'Earl'] >>>x = ['to', 'be', 'or', 'not', 'to', 'be'] >>>x.remove('be') >>>x ['to', 'or', 'not', 'to', 'be'] >>>x.remove('bee') Traceback (most recent call last): File "<input>", line 1, in <module> ValueError: list.remove(x): x not in list
-
修改
>>>x = [1, 1, 1] >>>x[1] = 2 >>>x [1, 2, 1] # 给切片赋值 >>>name = list('Perl') >>>name ['P', 'e', 'r', 'l'] #'ar'长度<=names[2:]的长度,name的长度不变 >>>name[2:] = list('ar') >>>name ['P', 'e', 'a', 'r'] >>>name = list('Perl') #'ython'长度>names[1:]的长度,name的长度变大 >>>name[1:] = list('ython') >>>name ['P', 'y', 't', 'h', 'o', 'n'] >>>numbers = [1, 5] #numbers[1:1]为空列表,该命令为在下标为1的位置插入列表[2, 3, 4] >>>numbers[1:1] = [2, 3, 4] >>>numbers [1, 2, 3, 4, 5] #该命令为删除元素numbers[1:4],即numbers列表中[1,4)位置的元素 >>>numbers[1:4]=[] >>>numbers [1, 5]
-
排序sort
sort函数对列表就地排序,不返回参数;
sorted函数不对列表进行修改,返回排序后的列表;>>>x = [4, 6, 2, 1, 7, 9] >>>x.sort() >>>x [1, 2, 4, 6, 7, 9] >>>x = [4, 6, 2, 1, 7, 9] >>>y = sorted(x) >>>x [4, 6, 2, 1, 7, 9] >>>y [1, 2, 4, 6, 7, 9] >>>sorted('Python') ['P', 'h', 'n', 'o', 't', 'y']
sort函数有两个参数:
1)key参数,类似于C++中的自定义排序函数cmp;
2)reverse参数,值为True/False,表示是否按照相反的顺序对列表进行排序>>>x = ['aardvark', 'abalone', 'acme', 'add', 'aerate'] >>>x.sort(key=len) >>>x ['add', 'acme', 'aerate', 'abalone', 'aardvark'] >>>x = [4, 6, 2, 1, 7, 9] >>>x.sort(reverse=True) >>>x [9, 7, 6, 4, 2, 1]
-
其他方法
append、extend、clear、copy、count、index、insert、pop
# append >>>lst = [1, 2, 3] >>>lst.append(4) >>>lst [1, 2, 3, 4] # extend #效率高于a = a + b #等效于a[len(a):] = b(可读性低) >>>a = [1, 2, 3] >>>b = [4, 5, 6] >>>a.extend(b) >>>a [1, 2, 3, 4, 5, 6] # clear >>>lst = [1, 2, 3] >>>lst.clear() >>>lst [] # copy >>>a = [1, 2, 3] >>>b = a >>>b[1] = 4 >>>a [1, 4, 3] >>>a = [1, 2, 3] >>>b = a.copy() >>>b[1] = 4 >>>a [1, 2, 3] # count >>>['to', 'be', 'or', 'not', 'to', 'be'].count('to') 2 >>>x = [[1, 2], 1, 1, [2, 1, [1, 2]]] >>>x.count(1) 2 >>>x.count([1, 2]) 1 # index(注意没找到将报错) >>knights = ['We', 'are', 'the', 'knights', 'who', 'say', 'ni'] >>>knights.index('who') 4 >>>knights.index('herring') Traceback (most recent call last): File "<input>", line 1, in <module> ValueError: 'herring' is not in list # insert >>>numbers = [1, 2, 3, 5, 6, 7] #等效于numbers[3:3] = ['four'](可读性低) >>>numbers.insert(3, 'four') >>>numbers [1, 2, 3, 'four', 5, 6, 7] # pop #基本操作 >>>x = [1, 2, 3] >>>x.pop() 3 >>>x [1, 2] >>>x.pop(0) 1 >>>x [2] # reverse >>>x = [1, 2, 3] >>>x.reverse() >>>x [3, 2, 1] #reversed函数返回一个迭代器,按相反的顺序迭代序列;list将返回的对象转换为列表; >>>x = [1, 2, 3] >>>list(reversed(x)) [3, 2, 1]
-
栈和队列的实现
栈的实现:
1)出栈pop(),入栈append(),即列表尾为栈顶
2)出栈pop(0),入栈insert(0, key),即列表首为栈顶队列的实现:
1)出队pop(0),入队append(),即列表头为队头,列表尾为队尾
2)出队pop(),入队insert(0, key),即列表头为队尾,列表尾为队头
3)使用模块collections中的deque,在后续学习中详细说明
3.元组
-
>>>1, 2, 3 (1, 2, 3) >>>(1, 2, 3) (1, 2, 3) >>>()#空元组 () >>>x = 1, 2, 3 >>>x[1] 2 >>>x[0:2] (1, 2) #创建只包含一个值的元组,一定注意使用逗号 >>>42, (42,) >>>(42,) (42,) #而>>>42只表示实数42 >>>3 * (40 + 2) 126 >>>3 * (40 + 2,) (42, 42, 42)
4.字符串
-
表示和连接
#单/双引号都表示字符串,正确的输入示例 >>>"Hello, World!" 'Hello, World!' >>>'Hello, World!' 'Hello, World!' #单双引号都有效是为了能在不使用引号转义的情况下,在字符串中使用单双引号,例如: >>>"Let's go!" "Let's go!" #如果仅使用单引号,即>>>'Let's go!',解释器将认为Let为字符串,从s开始即报错,输出 #SyntaxError: invalid syntax,或者使用引号转义 >>>'Let\'s go!' "Let's go!" #再例如 >>>'"Hello, world!" she said' '"Hello, world!" she said' #可以写作 >>>"\"Hello, world!\" she said" '"Hello, world!" she said' # 字符串拼接 >>>"Let's say " '"Hello, world!"' 'Let\s say "Hello, world!"' >>>"Hello, "+"world!" 'Hello, world!' >>>x = "Hello, " >>>y = "world!" >>>x + y 'Hello, world!' # 长字符串(可以跨行,用'''''') >>>print('''This is a very long string. It continues here. And it's not over yet. "Hello, world" Still here.''') # 原始字符串(用r) >>>print('C:\nowhere') C: owhere >>>print(r'C:\nowhere') C:\nowhere >>>print(r'This is illegal\') SyntaxError: EOL while scanning string literal
-
切片非法
>>>website = 'http://www.python.org' >>>website[-3:] = 'com' Traceback (most recent call last): File "<input>", line 1, in <module> TypeError: 'str' object does not support item assignment
-
格式化字符串
3种方法:
1) format % values 2) Template 3) "".format()
>>>format = "Hello, %s. %s enough for ya?" >>>values = ('world', 'Hot') >>>format % values 'Hello, world. Hot enough for ya?' >>>from string import Template >>>tmp1 = Template("Hello, $who! $what enough for ya?") >>>tmp1.substitute(who="Mars", what="Dusty") 'Hello, Mars! Dusty enough for ya?' >>>"{}, {} and {}".format("first", "second", "third") 'first, second and third' >>>"{0}, {1} and {2}".format("first", "second", "third") 'first, second and third' >>>"{3} {0} {2} {1} {3} {0}".format("be", "not", "or", "to") 'to be or not to be' >>>from math import pi >>>"{name} is approximately {value:.2f}.".format(value=pi, name="π") 'π is approximately 3.14.' >>>"{name} is approximately {value}.".format(value=pi, name="π") 'π is approximately 3.141592653589793.' >>>from math import e >>>f"Euler's constant is roughly {e}." "Euler's constant is roughly 2.718281828459045." # 等价于: >>>"Euler's constant is roughly {e}.".format(e=e) "Euler's constant is roughly 2.718281828459045."
5.字典
-
增
>>>phonebook = {'Beth':'9102', 'Alice':'2341', 'Cecil':'3258'} # 从列表和元组创建 >>>items = [('name', 'Gumby'), ('age', '42')] >>>d = dict(items) >>>d {'name': 'Gumby', 'age': '42'} >>>d['name'] 'Gumby' # 使用关键字实参 >>>d = dict(name='Gumby', age = 42) >>>d {'name': 'Gumby', 'age': 42} # 空字典 >>>d= dict() >>>d {} # fromkeys >>>{}.fromkeys(['name', 'age']) {'name': None, 'age': None} >>>dict.fromkeys(['name', 'age']) {'name': None, 'age': None} # 指定默认值 >>>dict.fromkeys(['name', 'age'], 'unknown') {'name': 'unknown', 'age': 'unknown'}
-
删
>>>x.clear() >>>del x['aaa'] # pop 获取与指定键相关联的值,并将该键-值对从字典中删除 >>>d = {'x':1, 'y':2} >>>d.pop('x') 1 >>>d {'y': 2} # popitem 随机地弹出一个字典项 >>>d = {'url':'http://www.python.org', 'spam':0, 'title':'Python Web Site'} >>>d.popitem() ('title', 'Python Web Site') >>>d {'url': 'http://www.python.org', 'spam': 0}
-
改
>>>d = { 'title':'Python Web Site', 'url':'http://www.python.org', 'changed':'Mar 14 22:09:15 MET 2016' } >>>x = {'title':'Python Language Website'} >>>d.update(x) >>>d {'title': 'Python Language Website', 'url': 'http://www.python.org', 'changed': 'Mar 14 22:09:15 MET 2016'}
-
查
k in d检查字典d是否包含键为k的项;
get方法(查找失败时不报错)
>>>d = {} >>>print(d['name']) Traceback (most recent call last): File "<input>", line 1, in <module> KeyError: 'name' >>>print(d.get('name')) None >>>d.get('name', 'N/A') 'N/A' >>>d['name'] = 'Eric' >>>d.get('name') 'Eric'
item
>>>d = {'title':'Python Web Site', 'url':'http://www.python.org', 'spam':0} >>>d.items() >>>dict_items([('title', 'Python Web Site'), ('url', 'http://www.python.org'), ('spam', 0)]) >>>it = d.items() >>>len(it) 3 >>>('spam', 0) in it True >>>d['spam'] = 1 >>>('spam', 0) in it False >>>d['spam'] = 0 >>>('spam', 0) in it True >>>list(d.items()) [('title', 'Python Web Site'), ('url', 'http://www.python.org'), ('spam', 0)]
keys
>>>d.keys() dict_keys(['title', 'url', 'spam'])
values
>>>d = {} >>>d[1] = 1 >>>d[2] = 2 >>>d[3] = 3 >>>d[4] = 1 >>>d.values() dict_values([1, 2, 3, 1])
获取指定键(参数1)的值,获取失败时在字典中添加键值对(参数1:参数2),参数2默认为None
>>>d = {} >>>d.setdefault('name', 'N/A') 'N/A' >>>d {'name': 'N/A'} >>>d['name'] = 'Gumby' >>>d.setdefault('name', 'N/A') 'Gumby' >>>d {'name': 'Gumby'} >>>d = {} >>>print(d.setdefault('name')) None >>>d {'name': None}
-
format_map
>>>phonebook = {'Beth':'9102', 'Alice':'2341', 'Cecil':'3258'} >>>phonebook {'Beth': '9102', 'Alice': '2341', 'Cecil': '3258'} "Cecil's phone number is {Cecil}.".format_map(phonebook) "Cecil's phone number is 3258."
-
深复制deepcopy和浅复制copy
>>>x = {'username':'admin', 'machines':['foo', 'bar', 'baz']} >>>y = x.copy() >>>y['username'] = 'mlh' >>>y['machines'].remove('bar') >>>y {'username': 'mlh', 'machines': ['foo', 'baz']} >>>x {'username': 'admin', 'machines': ['foo', 'baz']}
>>>from copy import deepcopy >>>d = {} >>>d['name'] = ['Alfred', 'Bertrand'] >>>c = d.copy() >>>dc = deepcopy(d) >>>d['name'].append('Clive') >>>c {'name': ['Alfred', 'Bertrand', 'Clive']} >>>dc {'name': ['Alfred', 'Bertrand']}