list 列表
list.index(n)
>>>l
[1, 2, 2, 3, 4]
>>>l.index(2) #返回2第一次出现的位置
1
>>>s='hello'
>>>ls=list(s)
>>>ls
['h', 'e', 'l', 'l', 'o']
>>>ls.index('e') #返回‘e’的索引
1
>>>ls.index('n') #返回错误,元素不存在
Traceback (most recent call last):
File "", line 1, in
ValueError: 'n' is not in list
list.count(n)
>>>l
[1, 2, 3, 4, 2, 3, 6, 8, 9]
>>>l.count(2) #返回2出现次数
2
>>>l.count(6)
1
>>>l.count(100) #返回0说明不存在
0
list.append(n)
>>>la=[3,6,9]
>>>lb=[0,1,2]
>>>la.append(521) #以元素形式追加末尾
>>>la
[3, 6, 9, 521]
>>>la.append(lb) ##以元素形式追加末尾
>>>la
[3, 6, 9, 521, [0, 1, 2]]
list.extend(list_n)
list_n必须为列表
>>>la.extend([888]) #扩充列表,list_n中的元素被逐个添加到原列表
>>>la
[3, 6, 9, 521, [0, 1, 2], 888]
>>>la.extend(lb)
>>>la
[3, 6, 9, 521, [0, 1, 2], 888, 0, 1, 2]
>>>la.extend(111) #直接传入元素会报错
Traceback (most recent call last):
File "", line 1, in
TypeError: 'int' object is not iterable
list.insert(index, n)
>>>g
[2, 3, 6, 8, 9]
>>>g.insert(2, 88888) #插入指定位置
>>>g
[2, 3, 88888, 6, 8, 9]
list.pop()/list.pop(n)
>>>g
[3, 88888, 6, 8]
>>>g.pop() #移除末尾元素
8
>>>g.pop(1) #移除指定元素
88888
>>>g
[3, 6]
list.remove(n)
>>>ls
['h', 'e', 'l', 'l', 'o']
>>>ls.remove('l') #移除指定元素
>>>ls
['h', 'e', 'l', 'o']
>>>ls.remove('z') #未知元素,报错
Traceback (most recent call last):
File "", line 1, in
ValueError: list.remove(x): x not in list
list_n.reverse()
>>>l=[1,2,3,4,5,6]
>>>l.reverse()
>>>l
[6, 5, 4, 3, 2, 1]
list_n.sort()
逆序
list_n.sort(reverse=True)
>>>ll
[1, 6, 3, 95, 56, 2, 565, 521]
>>>ll.sort() #对原列表ll排序
>>>ll
[1, 2, 3, 6, 56, 95, 521, 565]
>>>g
[3, 6]
>>>k=g.sort() #不返回任何值
>>>k==None
True
sorted(list_n)
逆序
sorted(list_n, reverse=True)
>>>l
[6, 5, 4, 3, 2, 1]
>>>k=sorted(l) #返回排序后列表,原列表不改变
>>>l
[6, 5, 4, 3, 2, 1]
>>>k
[1, 2, 3, 4, 5, 6]
list.sort(key=len)/list.sort(key=lambda...)
>>>lst=['a', 'aaaa', 'ab']
>>>lst.sort(key=len) #按长度len排序
>>>lst
['a', 'ab', 'aaaa']
>>> students = [
('john', 'B', 15),
('jane', 'A', 12),
('dave', 'B', 10),
('ethan', 'C', 20),
('peter', 'B', 20),
('mike', 'C', 16)
]
>>>
# 对第 3 列排序 (从小到大)
>>> sorted(students, key=lambda student: student[2])
[('dave', 'B', 10),
('jane', 'A', 12),
('john', 'B', 15),
('mike', 'C', 16),
('ethan', 'C', 20),
('peter', 'B', 20)]
# 对第 2 列排序(从小到大),再对第 3 列从大到小排序
>>> sorted(students, key=lambda student: (student[1], -student[2]))
[('jane', 'A', 12),
('peter', 'B', 20),
('john', 'B', 15),
('dave', 'B', 10),
('ethan', 'C', 20),
('mike', 'C', 16)]
tuple 元组
不可变序列
>>> a = (1, 2, 3) # a 是一个元组
>>> a
(1, 2, 3)
>>> a[0] = 6 # 元组是不可变的,不能对它进行赋值操作
Traceback (most recent call last):
File "", line 1, in
TypeError: 'tuple' object does not support item assignment
空元组
>>> a = ()
>>> a
()
一个值的元组
>>> a = (12,) # 在值后面再加一个逗号
>>> a
(12,)
>>> type(a)
>>>
>>> b = (12) # 只是使用括号括起来,而没有加逗号,不是元组,本质上是 b = 12
>>> b
12
>>> type(b)
tuple.index(n)
>>>t[0:]
(1, 2, 3)
>>>t[-1]
3
>>>t[1:]
(2, 3)
>>>t[1] #可按index访问元组元素
2
>>>t[0]
1
sorted(tuple_n)
>>>t=(1,2,3)
>>>sorted(t, reverse=True) #只能用sorted()而不能用tuple.sort(),因为tuple不可变
[3, 2, 1]
dict 字典
key必须为为不可变类型(数字/字符串/元组)
d=dict(name='jjf', age=20)
>>> d0 = {} # 空字典
>>> d0
{}
>>> d1 = {'name': 'ethan', 'age': 20}
>>> d1
{'age': 20, 'name': 'ethan'}
>>> d1['age'] = 21 # 更新字典
>>> d1
{'age': 21, 'name': 'ethan'}
>>> d2 = dict(name='ethan', age=20) # 使用 dict 函数
>>> d2
{'age': 20, 'name': 'ethan'}
>>> item = [('name', 'ethan'), ('age', 20)]
>>> d3 = dict(item)
>>> d3
{'age': 20, 'name': 'ethan'}
for key in dict_n:...
for k in dict_n.keys():...
del dict_n[key]
>>> d = {'name': 'ethan', 'age': 20}
>>> for key in d:
... print '%s: %s' % (key, d[key])
...
age: 20
name: ethan
>>> d['name']
'ethan'
>>> d['age']
20
>>> for key in d:
... if key == 'name':
... del d[key] # 要删除字典的某一项
...
Traceback (most recent call last):
File "", line 1, in
RuntimeError: dictionary changed size during iteration
>>>
>>> for key in d.keys(): # python2 应该使用这种方式, python3 使用 list(d.keys())
... if key == 'name':
... del d[key]
...
>>> d
{'age': 20}
in
>>> d = {'name': 'ethan', 'age': 20}
>>> 'name' in d
True
>>> d['score'] # 访问不存在的键,会抛出 KeyError
Traceback (most recent call last):
File "", line 1, in
KeyError: 'score'
>>> 'score' in d # 使用 in 判断 key 是否在字典里面
False
dict.clear()
>>> d = {'name': 'ethan', 'age': 20}
>>> rv = d.clear()
>>> d
{}
>>> print rv
None
-------------------------
>>> d1 = {}
>>> d2 = d1
>>> d2['name'] = 'ethan'
>>> d1
{'name': 'ethan'}
>>> d2
{'name': 'ethan'}
>>> d1.clear() # d1 清空之后,d2 也为空
>>> d1
{}
>>> d2
{}
-------------------------
>>> d1 = {}
>>> d2 = d1
>>> d2['name'] = 'ethan'
>>> d1
{'name': 'ethan'}
>>> d2
{'name': 'ethan'}
>>> d1 = {} # d1 变为空字典
>>> d2
{'name': 'ethan'} # d2 不受影响
dict['n_key'].remove('n_value')
dict_n.copy()
对不可变对象(key)修改保持同步
对可变对象(value)修改保持独立
>>> d1 = {'name': 'ethan', 'books': ['book1', 'book2', 'book3']}
>>> d2 = d1.copy()
>>> d2['name'] = 'peter' # d2 对不可变对象的修改不会改变 d1
>>> d2
{'books': ['book1', 'book2', 'book3'], 'name': 'peter'}
>>> d1
{'books': ['book1', 'book2', 'book3'], 'name': 'ethan'}
>>> d2['books'].remove('book2') # d2 对可变对象的修改会影响 d1
>>> d2
{'books': ['book1', 'book3'], 'name': 'peter'}
>>> d1
{'books': ['book1', 'book3'], 'name': 'ethan'}
>>> d1['books'].remove('book3') # d1 对可变对象的修改会影响 d2
>>> d1
{'books': ['book1'], 'name': 'ethan'}
>>> d2
{'books': ['book1'], 'name': 'peter'}
d=deepcopy(dict_n)
>>> from copy import deepcopy
>>> d1 = {'name': 'ethan', 'books': ['book1', 'book2', 'book3']}
>>> d2 = deepcopy(d1) # 创造出一个副本
>>>
>>> d2['books'].remove('book2') # 对 d2 的任何修改不会影响到 d1
>>> d2
{'books': ['book1', 'book3'], 'name': 'ethan'}
>>> d1
{'books': ['book1', 'book2', 'book3'], 'name': 'ethan'}
>>>
>>> d1['books'].remove('book3') # 对 d1 的任何修改也不会影响到 d2
>>> d1
{'books': ['book1', 'book2'], 'name': 'ethan'}
>>> d2
{'books': ['book1', 'book3'], 'name': 'ethan'}
dict.get('n_key')/dict.get('n_key', 'default_output')
>>> d = {}
>>> d['name']
Traceback (most recent call last):
File "", line 1, in
KeyError: 'name'
>>> print d.get('name')
None
>>> d.get('name', 'ethan') # 'name' 不存在,使用默认值 'ethan'
'ethan'
>>> d
{}
dict.setdefault(n_key, n_value)
键值对'n_key':'n_value'不存在时才会更新成功并返回‘n_value’
>>> d = {}
>>> d.setdefault('name', 'ethan') # 返回设定的默认值 'ethan'
'ethan'
>>> d # d 被更新
{'name': 'ethan'}
>>> d['age'] = 20
>>> d
{'age': 20, 'name': 'ethan'}
>>> d.setdefault('age', 18) # age 已存在,返回已有的值,不会更新字典
20
>>> d
{'age': 20, 'name': 'ethan'}
dict.update(dict_n)
以覆盖形式更新
>>> d = {}
>>> d1 = {'name': 'ethan'}
>>> d.update(d1) # 将字典 d1 添加到 d
>>> d
{'name': 'ethan'}
>>> d2 = {'age': 20}
>>> d.update(d2) # 将字典 d2 添加到 d
>>> d
{'age': 20, 'name': 'ethan'}
>>> d3 = {'name': 'michael'} # 将字典 d3 添加到 d,存在相同的 key,则覆盖
>>> d.update(d3)
>>> d
{'age': 20, 'name': 'michael'}
for k, v in dict.items():...
返回列表
>>> d = {'name': 'ethan', 'age': 20}
>>> d.items()
[('age', 20), ('name', 'ethan')]
>>> for k, v in d.items():
... print '%s: %s' % (k, v)
...
age: 20
name: ethan
for k, v in dict.iteritems():...
返回迭代器对象
>>> d = {'name': 'ethan', 'age': 20}
>>> d.iteritems()
>>> for k, v in d.iteritems():
... print '%s: %s' % (k, v)
...
age: 20
name: ethan
dict.keys()
dict.iterkeys()
>>> d = {'name': 'ethan', 'age': 20}
>>> d.keys()
['age', 'name'] #返回针对键列表
>>> d.iterkeys()
#返回针对键迭代器
dict.values()
dict.itervalues()
>>> d = {'name': 'ethan', 'age': 20}
>>> d.values()
[20, 'ethan']
>>> d.itervalues()
dict.pop('n_key')
>>> d = {'name': 'ethan', 'age': 20}
>>> d.pop('name') #移除键值对,返回键对应值
'ethan'
>>> d
{'age': 20}
dict.popitem()
>>> d = {'id': 10, 'name': 'ethan', 'age': 20}
>>> d.popitem()
('age', 20)
>>> d
{'id': 10, 'name': 'ethan'}
>>> d.popitem() #随机挑一个(幸运观众hhh...)键值对移除
('id', 10)
>>> d
{'name': 'ethan'}
sorted(dict_n, key=lambda...)
students = [
{'name': 'john', 'score': 'B', 'age': 15},
{'name': 'jane', 'score': 'A', 'age': 12},
{'name': 'dave', 'score': 'B', 'age': 10},
{'name': 'ethan', 'score': 'C', 'age': 20},
{'name': 'peter', 'score': 'B', 'age': 20},
{'name': 'mike', 'score': 'C', 'age': 16}
]
------------------------------------------------
>>> sorted(students, key=lambda stu: stu['score']) # score 从小到大
[{'age': 12, 'name': 'jane', 'score': 'A'},
{'age': 15, 'name': 'john', 'score': 'B'},
{'age': 10, 'name': 'dave', 'score': 'B'},
{'age': 20, 'name': 'peter', 'score': 'B'},
{'age': 20, 'name': 'ethan', 'score': 'C'},
{'age': 16, 'name': 'mike', 'score': 'C'}]
------------------------------------------------
>>> sorted(students, key=lambda stu: stu['score'], reverse=True) # score 从大到小
[{'age': 20, 'name': 'ethan', 'score': 'C'},
{'age': 16, 'name': 'mike', 'score': 'C'},
{'age': 15, 'name': 'john', 'score': 'B'},
{'age': 10, 'name': 'dave', 'score': 'B'},
{'age': 20, 'name': 'peter', 'score': 'B'},
{'age': 12, 'name': 'jane', 'score': 'A'}]
------------------------------------------------
>>> sorted(students, key=lambda stu: (stu['score'], stu['age'])) # 先 score 从小到大,再 age 从小到大
[{'age': 12, 'name': 'jane', 'score': 'A'},
{'age': 10, 'name': 'dave', 'score': 'B'},
{'age': 15, 'name': 'john', 'score': 'B'},
{'age': 20, 'name': 'peter', 'score': 'B'},
{'age': 16, 'name': 'mike', 'score': 'C'},
{'age': 20, 'name': 'ethan', 'score': 'C'}]
------------------------------------------------
>>> sorted(students, key=lambda stu: (stu['score'], -stu['age'])) # 先 score 从小到大,再 age 从大到小
[{'age': 12, 'name': 'jane', 'score': 'A'},
{'age': 20, 'name': 'peter', 'score': 'B'},
{'age': 15, 'name': 'john', 'score': 'B'},
{'age': 10, 'name': 'dave', 'score': 'B'},
{'age': 20, 'name': 'ethan', 'score': 'C'},
{'age': 16, 'name': 'mike', 'score': 'C'}]
set 集合
key不可重复
s=set(n)
创建
>>> s1 = {'a', 'b', 'c', 'a', 'd', 'b'} # 使用 {}
>>> s1
set(['a', 'c', 'b', 'd'])
>>>
>>> s2 = set('helloworld') # 使用 set(),接收一个字符串
>>> s2
set(['e', 'd', 'h', 'l', 'o', 'r', 'w'])
>>>
>>> s3 = set(['.mp3', '.mp4', '.rmvb', '.mkv', '.mp3']) # 使用 set(),接收一个列表
>>> s3
set(['.mp3', '.mkv', '.rmvb', '.mp4'])
for e in s:...
遍历
>>> s = {'a', 'b', 'c', 'a', 'd', 'b'}
>>> for e in s:
... print e
...
a
c
b
d
set.add(n)
>>> s = {'a', 'b', 'c', 'a', 'd', 'b'}
>>> s
set(['a', 'c', 'b', 'd'])
>>> s.add('e') #添加
>>> s
set(['a', 'c', 'b', 'e', 'd'])
>>> s.add('a') #重复添加无效
>>> s
set(['a', 'c', 'b', 'e', 'd'])
>>> s.add(4)
>>> s
set(['a', 'c', 'b', 4, 'd', 'e'])
set.remove(n)
set.discard(n)
>>> s = {'a', 'b', 'c', 'a', 'd', 'b'}
>>> s
set(['a', 'c', 'b', 'd'])
>>> s.remove('a') # 删除元素 'a'
>>> s
set(['c', 'b', 'd'])
>>> s.remove('e') # 删除不存在的元素,会抛出 KeyError
Traceback (most recent call last):
File "", line 1, in
KeyError: 'e'
>>> s.discard('e') # 删除不存在的元素, 不会抛出 KeyError
交&并|差-子集判断set.issubset(set_n)
>>> s1 = {1, 2, 3, 4, 5, 6}
>>> s2 = {3, 6, 9, 10, 12}
>>> s3 = {2, 3, 4}
>>> s1 & s2 # 交集
set([3, 6])
>>> s1 | s2 # 并集
set([1, 2, 3, 4, 5, 6, 9, 10, 12])
>>> s1 - s2 # 差集
set([1, 2, 4, 5])
>>> s3.issubset(s1) # s3 是否是 s1 的子集
True
>>> s3.issubset(s2) # s3 是否是 s2 的子集
False
>>> s1.issuperset(s3) # s1 是否是 s3 的超集
True
>>> s1.issuperset(s2) # s1 是否是 s2 的超集
False
string 字符串
indexing/sliceing/add/multiplying
>>> s = 'hello, '
>>> s[0] # 索引
'h'
>>> s[1:3] # 分片
'el'
>>> s + 'world' # 加法
'hello, world'
>>> s * 2 # 乘法
'hello, hello, '
string[n]
>>> nums = [1, 2, 3, 4, 5] # 列表
>>> nums[0]
1
>>> nums[1]
2
>>> nums[-1] # 索引 -1 表示最后一个元素
5
>>> s = 'abcdef' # 字符串
>>> s[0]
'a'
>>> s[1]
'b'
>>>
>>> a = (1, 2, 3) # 元组
>>> a[0]
1
>>> a[1]
2
string[a:b]
>>> numbers = [1, 2, 3, 4, 5, 6]
>>> numbers[0:2] # 列表分片
[1, 2]
>>> numbers[2:5]
[3, 4, 5]
>>> s = 'hello, world' # 字符串分片
>>> s[0:5]
'hello'
>>> a = (2, 4, 6, 8, 10) # 元组分片
>>> a[2:4]
(6, 8)
-----------------------------------------------------
>>> numbers = [1, 2, 3, 4, 5, 6, 7, 8]
>>> numbers[-3:]
[6, 7, 8]
>>> numbers[5:]
[6, 7, 8]
-----------------------------------------------------
>>> numbers = [1, 2, 3, 4, 5, 6, 7, 8]
>>> numbers[0:4]
[1, 2, 3, 4]
>>> numbers[0:4:1] # 步长为 1,不写也可以,默认为 1
[1, 2, 3, 4]
>>> numbers[0:4:2] # 步长为 2,取出 numbers[0], numbers[2]
[1, 3]
>>> numbers[::3] # 等价于 numbers[0:8:3],取出索引为 0, 3, 6 的元素
[1, 4, 7]
-----------------------------------------------------
>>> numbers = [1, 2, 3, 4, 5, 6, 7, 8]
>>> numbers[0:4:-1]
[]
>>> numbers[4:0:-1] # 取出索引为 4, 3, 2, 1 的元素
[5, 4, 3, 2]
>>> numbers[4:0:-2] # 取出索引为 4, 2 的元素
[5, 3]
>>> numbers[::-1] # 从右到左取出所有元素
[8, 7, 6, 5, 4, 3, 2, 1]
>>> numbers[::-2] # 取出索引为 7, 5, 3, 1 的元素
[8, 6, 4, 2]
>>> numbers[6::-2] # 取出索引为 6, 4, 2, 0 的元素
[7, 5, 3, 1]
>>> numbers[:6:-2] # 取出索引为 7 的元素
[8]
string1+string2
>>> [1, 2, 3] + [4, 5, 6] # 「加法」效果其实就是连接在一起
[1, 2, 3, 4, 5, 6]
>>> (1, 2, 3) + (4, 5, 6)
(1, 2, 3, 4, 5, 6)
>>> 'hello, ' + 'world!'
'hello, world!'
>>> [1, 2, 3] + 'abc'
Traceback (most recent call last):
File "", line 1, in
TypeError: can only concatenate list (not "str") to list
string*n
>>> 'abc' * 3
'abcabcabc'
>>> [0] * 3
[0, 0, 0]
>>> [1, 2, 3] * 3
[1, 2, 3, 1, 2, 3, 1, 2, 3]
in
>>> 'he' in 'hello'
True
>>> 'hl' in 'hello'
False
>>> 10 in [6, 8, 10]
True
string.find(n, pos)
>>> motto = "to be or not to be, that is a question"
>>> motto.find('be') # 返回 'b' 所在的位置,即 3
3
>>> motto.find('be', 4) # 指定从起始位置开始找,找到的是第 2 个 'be'
16
>>> motto.find('be', 4, 7) # 指定起始位置和终点位置,没有找到,返回 -1
-1
string.split(n)
>>> '/user/bin/ssh'.split('/') # 使用 '/' 作为分隔符
['', 'user', 'bin', 'ssh']
>>> '1+2+3+4+5'.split('+') # 使用 '+' 作为分隔符
['1', '2', '3', '4', '5']
>>> 'that is a question'.split() # 没有提供分割符,默认使用所有空格作为分隔符
['that', 'is', 'a', 'question']
n.join(string_list)
>>> '/'.join(['', 'user', 'bin', 'ssh'])
'/user/bin/ssh'
>>>
>>> '+'.join(['1', '2', '3', '4', '5'])
'1+2+3+4+5'
>>> ' '.join(['that', 'is', 'a', 'question'])
'that is a question'
>>> ''.join(['h', 'e', 'll', 'o'])
'hello'
>>> '+'.join([1, 2, 3, 4, 5]) # 不能是数字
Traceback (most recent call last):
File "", line 1, in
TypeError: sequence item 0: expected string, int found
string.strip()
string.lstrip()
string.rstrip()
>>> ' hello world! '.strip() # 移除左右两侧空格
'hello world!'
>>> '%%% hello world!!! ####'.strip('%#') # 移除左右两侧的 '%' 或 '#'
' hello world!!! '
>>> '%%% hello world!!! ####'.strip('%# ') # 移除左右两侧的 '%' 或 '#' 或空格
'hello world!!!'
#另
>>> s=' BlackPink Lisa '
>>> s.lstrip() #只移除左侧
'BlackPink Lisa '
>>> s.rstrip() #只移除右侧
' BlackPink Lisa'
>>> s.strip()
'BlackPink Lisa'
>>>
string.replace(word, new_word)
>>> motto = 'To be or not To be, that is a question'
>>> motto.replace('To', 'to') # 用 'to' 替换所有的 'To',返回了一个新的字符串
'to be or not to be, that is a question'
>>> motto # 原字符串保持不变
'To be or not To be, that is a question'
string.maketrans('aeiou', '12345')
string.translate(table[, delete_chars])
>>> from string import maketrans
>>> table = maketrans('aeiou', '12345')
>>> motto = 'to be or not to be, that is a question'
>>> motto.translate(table)
't4 b2 4r n4t t4 b2, th1t 3s 1 q52st34n'
>>> motto
'to be or not to be, that is a question'
>>> motto.translate(table, 'rqu') # 移除所有的 'r', 'q', 'u'
't4 b2 4 n4t t4 b2, th1t 3s 1 2st34n'
string.lower()
string.upper()
>>> x = 'PYTHON'
>>> x.lower()
'python'
>>> x
'PYTHON'
>>>
>>> y = 'python'
>>> y.upper()
'PYTHON'
>>> y
'python'
参考
explore-python/DataTypes