首页 › 日存档 › 2010年04月21日

python学习(1)-字典 (Dictionary)

字典(Dictionary)是一种映射结构的数据类型,由无序的“键-值对”组成。字典的键必须是不可改变的类型,如:字符串,数字,tuple;值可以为任何python数据类型。

1、新建字典
>>> dict1={} #建立一个空字典
>>> type(dict1)
<type ‘dict’>

2、增加字典元素:两种方法
>>> dict1['a']=1 #第一种
>>> dict1
{‘a’: 1}
#第二种:setdefault方法
>>> dict1.setdefault(‘b’,2)
2
>>> dict1
{‘a’: 1, ‘b’: 2}

3、删除字典
#删除指定键-值对
>>> dict1
{‘a’: 1, ‘b’: 2}
>>> del dict1['a'] #也可以用pop方法,dict1.pop(‘a’)
>>> dict1
{‘b’: 2}
#清空字典
>>> dict1.clear()
>>> dict1 #字典变为空了
{}
#删除字典对象
>>> del dict1
>>> dict1
Traceback (most recent call last):
File “<interactive input>”, line 1, in <module>
NameError: name ‘dict1′ is not defined
继续阅读 »

Python随机函数

模 块:random
randint():接受起始终止位置的两个整数,返回其间的随机整数
randrange() :接受和range()函数一样的参数,随机返回range([start,]stop[,step])结果的一项
uniform() :几乎和randint()一样, 不过它返回的是二者之间的一个浮点数(不包括范围上限)
random() :类似 uniform() 只不过下限恒等于 0.0,上限恒等于 1.0
choice() :随机返回给定序列的一个元素

#!/usr/bin/python
“test python’s inner module random”
N=int(raw_input(‘Enter N: ‘))
n=int(raw_input(‘Enter n: ‘))
m=int(raw_input(‘Enter m: ‘))
继续阅读 »