#-*- 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
python学习字典
最新推荐文章于 2024-02-27 22:17:49 发布