python数据结构是通过某种方式(例如对元素进行编号)组织在一起的数据元素的集合,这些数据元素可以是数字或字符,甚至可以是其他数据结构。
在python中,最基本的数据结构是序列(sequence)。
序列中的每个元素被分配一个序号---即元素的位置,也被为索引。
edward = ['Edward Gumby',42]
greeting = 'hello' greeting[0] 输出: h
tag = '<a href="http://www.python.org">Python web sit</a>' tag[9:30] tag[32:-4]
x = [1,1,1] x[1] = 2 x 输出:[1,2,1]
names = ['Alice','Beth','Cecil','Dee-Dee'] del names[2] names 输出:['Alice','Beth','Dee-Dee']
name = list('Perl') name name[2:] = list('ar') name 输出:['P','e','a','r']分片赋值语句可以在不需要替换任何原有元素的情况下插入新的元素
numbers = [1,5] numbers[1:1] = [2,3,4] numbers 输出:[1,2,3,4,5]
lst = [1,2,3] lst.append(4) lst 输出:[1,2,3,4]
['to' 'be' 'or' 'not' 'to' 'be'].count('to')
a = [1,2,3] b = [4,5,6] a.extend(b) a 输出:[1,2,3,4,5,6]
a = [1,2,3] b = [4,5,6] a[len(a):] = b a 输出结果一样
knights = ['We','are','the','knights','who','say','ni'] knights.index('who')
numbers = [1,2,3,4,5,6,7] numbers.insert(3,'four') 输出: [1,2,3,'four',5,6,7]与extend方法一样,insert方法的操作也可以用分片赋值来实现
x = [1,2,3] x.pop() 3 x [1,2]
x = ['to','be','or','not','to','be'] x.remove('be')
x = [4,6,2,1,7,9] x.sort() x 输出: [1,2,4,6,7,9]
x = [4,6,2,1,7,9] y = x[:] y.sort() y 输出和上面结果一样
x = [4,6,,2,1,7,9] y = sorted(x.)
cmp(42,32) 输出:1 cmp(99,100) 输出:-1 cmp(10,10) 输出:0 numbers = [5,2,9,7] numbers.sort(cmp) numbers [2,5,7,9]
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]
1,2,3 (1,2,3)
(1,2,3)
()
42,
3*(40+2,) 输出: (42,42,42)
tuple([1,2,3]) 输出:(1,2,3) tuple('abc') 输出:('a','b','c') tuple((1,2,3)) 输出:(1,2,3)
cmp(x,y) | 比较两个值 |
len(seq) | 返回序列的长度 |
list(seq) | 把序列转换成列表 |
max(args) | 返回序列或者参数集合中的最大值 |
min(args) | 返回序列或者参数集合中的最小值 |
reversed(seq) | 对序列进行反向迭代 |
sorted(seq) | 返回已排序的包含seq所有元素的列表 |
tuple(seq) | 把序列转换成元组 |