python学习字典

#-*- encoding: utf-8 -*-
'''
Created on 2013-1-7

@author: 
'''
#列表和序列的访问索引只能是整数,但是字典的访问索引可以是整数,也可以是字符串
#字典的元素以逗号为分隔符,每个元素包含键和键值,他俩用冒号分隔
diction1 = {1:"tieto",2:"nsn"}
print diction1
#创建空字典,再添加元素
diction2 = {}
diction2["one"] = "yes"
diction2["two"] = "no"
diction2["three"] = "haha"
diction3 = diction2.copy()
print diction2
del diction2["three"]
print diction2
print len(diction2) #2
diction2.clear()
print len(diction2) #0
#字典是可变的。如果你想修改字典,并且保留原来的备份,就要用到字典的copy方法
print diction3 #diction3是diction2的拷贝,diction2 已经被clear了

#matrix = [ [0,0,0,1,0],
#            [0,0,0,0,0],
#            [0,2,0,0,0],
#            [0,0,0,0,0],
#            [0,0,0,3,0] ]
#也可以用字典表示矩阵。该矩阵的非零元素的键用含有两个整数元素
#的序列表示,分别代表行和列。
matrix = {(0,3): 1, (2, 1): 2, (4, 3): 3}
print matrix
#我们不能得到值为零的元素,因为这个矩阵中,没有非零值的键。
print matrix[0,3]
#print matrix[0,2], this is error, no key
#get方法解决了这个问题。
#第一个参数是键;第二个参数表示:如果该键没有出现在字典中,那末这
#个键的值就是第二个参数
print matrix.get((0,2),0)
#python用一种叫做长整数的类型处理任意大小的整数。通常,我们用
#整数后面加一个大写的L 表示长整数。
print type(3L) #long
print long(3.5) #3
print long("35")  #35  
#计算字符串字符个数
leters ="thisisstringcount"
def dicount(str):
    diccount= {}
    for i in str:
        diccount[i] = diccount.get(i,0) + 1;
    return diccount       

print dicount(leters)

#Python有两个函数items和sort能够更好的完成这一功能
letrcount = dicount(leters).items()
print letrcount
letrcount.sort()
print letrcount

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值