【Python】Python数据结构
列表(list)
list是可以修改的(字符串和Tuple则不能修改)
列表中的常用方法
list.append(x) #把x加入表尾
list.insert(i,x) #在第i个元素之前插入x
list.remove(x) #删除列表中值为x的第一个元素
list.count(x) #返回x在列表中出现的次数
list.sort() #排序
list.reverse() #倒排
list.index(x) #返回列表中第一个x的索引
list.pop() #弹出最后一个元素(也可以传入参数使删除某个值)
将列表当做堆栈使用
stack = [3,4,5]
stack.append(6) #相当于push
stack.pop() #pop
将列表当做队列使用
from collections import deque
queue = deque(["Eric","John","Michael"])
queue.append("Terry") #相当于push
queue.popleft() #相当于pop
列表推导式
列表推导式提供了从序列创建列表的简单途径。通常应用程序将一些操作应用于某个序列的每个元素,用其获得的结果作为生成新列表的元素,或者根据确定的判定条件创建子序列。
每个列表推导式都在for之后跟一个表达式,然后有零到多个for或if子句。返回结果是一个根据表达从其后的for和if上下文环境中生成出来的列表。如果希望表达式推导出一个元组,就必须使用括号。
如
>>> vec = [2, 4, 6]
>>> [3*x for x in vec]
[6, 12, 18]
>>> [[x, x**2] for x in vec]
[[2, 4], [4, 16], [6, 36]]
可以对序列里每一个元素逐个调用某个方法
>>> freshfruit = [‘ banana‘, ‘ loganberry ‘, ‘passion fruit ‘]
>>> [weapon.strip() for weapon in freshfruit]
[‘banana‘, ‘loganberry‘, ‘passion fruit‘]
可以用if子句作为过滤器
>>> [3*x for x in vec if x > 3]
[12, 18]
>>> [3*x for x in vec if x < 2]
[]
下面是一些关于循环和其他技巧的展示
>>> vec1 = [2, 4, 6]
>>> vec2 = [4, 3, -9]
>>> [x*y for x in vec1 for y in vec2]
[8, 6, -18, 16, 12, -36, 24, 18, -54]
>>> [x+y for x in vec1 for y in vec2]
[6, 5, -7, 8, 7, -5, 10, 9, -3]
>>> [vec1[i]*vec2[i] for i in range(len(vec1))]
[8, 12, -54]
列表推导式可以使用复杂表达式或嵌套函数
>>> [str(round(355/113, i)) for i in range(1, 6)]
[‘3.1‘, ‘3.14‘, ‘3.142‘, ‘3.1416‘, ‘3.14159‘]
嵌套列表解析
python中的列表也可以嵌套。
如一个3*4的矩阵列表
>>> matrix = [
... [1, 2, 3, 4],
... [5, 6, 7, 8],
... [9, 10, 11, 12],
... ]
将3X4列表转换为4X3列表:
方法1
>>> [[row[i] for row in matrix] for i in range(4)]
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
方法2
>>> transposed = []
>>> for i in range(4):
... transposed.append([row[i] for row in matrix])
...
>>> transposed
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
方法3
>>> 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
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
del语句
使用del语句可以从一个List中按照索引而不是值来删除一个元素。
可以用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
[]
元组(Tuple)
元组由若干逗号分隔的值组成,例如
>>> t = 12345, 54321, ‘hello!‘
>>> t[0]
12345
>>> t
(12345, 54321, ‘hello!‘)
>>> # Tuples may be nested:
... u = t, (1, 2, 3, 4, 5)
>>> u
((12345, 54321, ‘hello!‘), (1, 2, 3, 4, 5))
元组在输出的时候是有括号的,以便于正确表达嵌套结构。
在输入时可能有或没有括号,不过括号通常是必须的(如果元组是更大的表达式一部分的话)
集合(Sets)
集合是一个无序不重复元素的集。基本功能包括关系测试和消除重复元素。
可以用大括号{}创建集合。但如果要创建空集合要使用set()
集合的演示:
>>> 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‘}>>> 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‘}
字典(Dictionaries)
字典以关键字为索引,关键字可以使任意不可变类型,通常用字符串或数值。在同一个字典中,关键字必须是互不相同。
一对大括号创建一个空的字典。
字典例子
>>> 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‘, 4098)])
{‘sape‘: 4139, ‘jack‘: 4098, ‘guido‘: 4127}
另外 字典推导也可以用来创建任意键和值得表达式词典
如
>>> {x: x**2 for x in (2, 4, 6)}
{2: 4, 4: 16, 6: 36}
如果关键字是简单的字符串,也可以使用关键字参数指定键值对有时候更方便
>>> dict(sape=4139, guido=4127, jack=4098)
{‘sape‘: 4139, ‘jack‘: 4098, ‘guido‘: 4127}
遍历技巧
在字典中遍历时,关键字和对应的值可以使用items()方法同时解读出来!
如
knights = {‘gallahad‘:‘the pure‘,‘robin‘:‘the brave‘}
for k,v in knights.items();
print(k,v)
>>>gallahad the pure
>>>robin the brave
在列表中遍历时,索引位置和对应值可以使用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‘s your {0}?It is {1}.".format(q,a))
要反向遍历一个序列,首先指定这个序列,然后调用reversesd()函数
如
for i in reversed(range(1,10,2)):
print(i)
>>>9
>>>7
>>>5
>>>3
>>>1
要按顺序遍历一个序列,使用sorted()函数返回一个已经排序的序列(并不修改原值)
basket = [‘apple‘,‘pear‘,‘apple‘,‘banana‘]
for f in sorted(set(basket)):
print f
>>>apple
>>>banana
>>>pear
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。