Container 容器:存放其他对象的对象
1. Sequence 序列:每个元素都被分配一个序号。
Python内建序列(6种):元组,列表,字符串,Unicode字符串,buffer 对象,xrange 对象
操作——对序列:
1. indexing 索引(一定要注意从零开始)
greet = 'hello'
print greet[0],greet[-1]
print 'hello'[0],'hello'[-1] # use index directly to sequence:list/tuple/string...
print raw_input('Enter "hello":')[0],raw_input('Enter "hello":')[-1]
2. slicing 分片
nums = [1,2,3,4,5,6,7,8,9]
print nums[3:6], nums[0:1],nums[3:],nums[:6]
print nums[-1:-3],nums[-3:-1],nums[-3:0] # index 0 is front of -3
print nums[-3:],nums[:-3]# including first/last element of sequence
print nums[:],nums[::1],nums[::2],nums[::3]
print nums[::-1],nums[0:10:-2],nums[10:0:-2] # 2nd < 1st if step size is nagtive
3. adding 加 / multiplying 乘
sequence = [None] * 10
print sequence
str = 'hello'
num = 5
print str + num
4. 成员资格 in
Python 2.3 以后是可以判断字符串是否存在字符串里面的
str = 'hello world'
print 'hello' in str
核对密码:
database = [
['a','123'],
['b','456'],
['c','789']
]
username = raw_input('username is : ')
psw = raw_input('password is : ')
if [username,psw] in database:
print 'Access granted'
else:
print 'Access denied'
5. len() , max(), min() 节省时间
2. 映射:每个元素都有一个名字(键)
字典
3. set 集合
这里集合的意义跟数学上集合的意义是一致的(会去重),所以它主要用于检查成员资格。集合是可变的(使用frozenset() 将集合不可变),不能作为字典的键
特点:集合是无序的;集合中的元素是唯一的;
因为是集合,所以数学上对集合的操作同样适用:求交集,并集。
4. 堆
Python 没有单独的对类型——只有一个包含一些堆操作函数的模块 heapq。
建立好一个堆:
from heapq import *
from random import shuffle
data = range(10)
shuffle(data)
print data
heap = []
for n in data:
heappush(heap,n)
print heap
堆的排位规则:i 位置的元素总比 2*i,2*i+1 位置的元素小——堆属性
也可以通过如下操作进行堆的建立:
from heapq import *
from random import shuffle
data = range(10)
shuffle(data)
print data
heap = []
for n in data:
heappush(heap,n)
print heap
heapify(data)
print data