Python 的数据结构

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



  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值