python之映射与集合类型

上一篇 / 下一篇  2013-10-17 21:47:44 / 个人分类:python

#字典是python唯一的映射类型,映射类型对象里哈希值(key)和指向的对象(value)是一对多的关系,字典类型和序列类型的区别:存储和访问的方式不一样
#映射类型通常被叫做哈希表,因为字典类型就是哈希类型。字典是无序的(因为哈希是无序的),字典有keys(),values(),items(),hash表一般有很好的性能,因此查询相当快
#1、创建字典:只需把字典赋值给一个变量,不管这个字典是否包含元素
dict1 = {}
dict2= {'name':'earth','port':80}
print dict1,dict2
    #使用工厂方法dict()来创建字典
dict3 = dict((['x',1],['y',2]))
print dict3
print dict((('x',1),['y',2]))
dict4 = {}.fromkeys(('x','y'),-1)  #fromkeys()创建一个默认的字典,字典元素具有相同的值
print dict4                         #{'y': -1, 'x': -1}
dict4 = {}.fromkeys(('x','y'))  #fromkeys()没给出默认的值,则默认为None 
print dict4                     #{'y': None, 'x': None}
#2、访问字典中的值:若访问的元素不存在,则抛出异常
dict2= {'name':'earth','port':80}
for key ,value in dict2.items() :print ('key = %s and value = %s')%(key ,value)
for key in dict2.keys() :print('key = %s and value = %s')%(key ,dict2[key])
for key in dict2 :print key     #key值得获取可以不用使用key()方法。但是去的value值必须使用.value()方法
for value in dict2.values():print value
    #判断字典中是否存在该key
print dict2.has_key('name')     #第一中方法
print 'na' in dict2        #第二种方法
print 'na' not in dict2    #True
#3、更新字典:添加或删除一个已经存在的数据
dict2['stuid'] = '201010414440'  #增加
dict2['arch'] = 'suno6'     #增加
dict2['name'] = 'zhaoyezi'   #更改
print 'host %(name)s is running on port %(port)d'%dict2   #这是一种新的输出方式:其中name /port 是dict2的值
#4、删除字典元素
del dict2['name']  #删除字典的键为name的条目
print dict2
#dict2.clear()       #清除dict2的所有条目
#del dict2          #删除整个字典
print dict2.pop('port')  #删除平返回键为name的条目
#5、映射类型的操作符
    #标准操作符
dict1 = {'abc':123}
dict2 = {'aBc':123}
print dict1 > dict2
#6、映射类型的内建函数和工厂函数
    #标准类型函数type() str() cmp()
    #字典比较算法:首先是字典的元素的个数(那个多,那个大),个数相同时,比较键(依次比较,当遇到不同的,哪个大,那就那个字典大),若元素个数,键都一样,依次比较值,那个值大就那个大。如果都一样,则返回0,一样大
dict1 = {'abc':123}
dict2 = {'aBc':123,'x':12}
print cmp(dict1,dict2)    #-1:因为dict1只有一个元素,dict2有两个元素
dict1 = {'abc':123,'port':900}
dict2 = {'aBc':123,'x':12}
print cmp(dict1,dict2)            #1,个数相同,比较键:dict1 的键大于dict2的键
dict1 = {'abc':123,'port':900}
dict2 = {'abc':123,'port':12}
print cmp(dict1,dict2)          #1 :个数相同,键相同,第一个值相同,dict1 的900 大于dict2的12,如果12改为900,返回0

    #映射类型相关的函数
    #工厂函数dict():传递的参数可以是迭代的,即序列。但是必须成对出现,一个是键,一个是值
print dict(zip(['x',1],['y',2]))    #{'x': 'y', 1: 2}
print dict((('x',1),('y',2)))         #{'x':1,'y':2}
print dict([('xy'[i-1],i) for i in range(1,3)]) #{'y': 2, 'x': 1}
print dict(x = 1,y = 2)
dict1 = dict(x = 1,y = 2)
dict2 = dict1
print dict2
print len(dict2)  #算出字典的键值对有多少个   ,输出2
    #hash()函数:判断某个对象是否可以做为一个字典的键,会返回一个这个对象的hash值,只有这个对象时可hash的,才能做为字典的键,否则会出现异常
#hash([])  #TypeError: unhashable type: 'list'
#7、映射类型内建方法
dict2= {'name':'earth','port':80}
print dict2.keys()
print dict2.values()
print dict2.items()   #[('name', 'earth'), ('port', 80)]
for eachkey in dict2.keys():print eachkey
for eachkey in dict2 :print eachkey
# dict2.clear()  清楚所有的值
print dict.fromkeys('x,y',-3)   #创建相同值得字典,初始值为-3,如果没有设置-3则为None   {'y': -3, 'x': -3, ',': -3}
print dict2.get('name')   #返回name所对应的值,如果没有,则返回None
print dict2.has_key('name')  #返回True  False.
print dict2.pop('name')  #earth
dict2.setdefault('name','zhaoyehong')  #设置值,如果没有设置值,则将name的值设置为None  {'name': 'zhaoyehong', 'port': 80}
print dict2
dict3  ={'stuid':123456}
dict3.update(dict2)#将dict2字典放多dict3中
print dict3  #{'stuid': 123456, 'name': 'zhaoyehong', 'port': 80}
    #不运行一个键对应多个值:当有键发生冲突时,取最后一个值
    #大多数对象可以作为键,但是它们必须是可哈希的,像序列list ,字典这样的可变类型,不可哈希,不能作为键
    #所有不可变的类型都是可哈希的,都可以作为键。但是要说明:数字,值相等时是一个键,如1 和1.0 ,如果要元组作为键:那么元组中只能包含像数字、字符串这样的不可变参数
#8、字典例子:用于管理用户名和密码的模拟登陆数据系统:当用户账号创建,用户可以用自己的账号和密码重新登录。新用户不能使用与别人相同的账号
db = {}
def newuser():
    prompt = 'login desired:'
    while True:
        name = raw_input(prompt)
        if db.has_key(name):
            prompt = 'name taken,try another:'
            continue
        else:
            break
    pwd = raw_input('password:')
    db[name]  = pwd
def olduser():
    name = raw_input('login:')
    password = raw_input('password:')
    if password == db.get(name):
        print 'welcome back',name
    else:
        print 'login incorrect'
def showmenu():
    prompt = '''
    (N)ew User Login
    (E)xisting User Login
    (Q)uit
    enter choice:
'''
    done = False
    while not done:
        chosen = False
        while not chosen:
            try:
                choice = raw_input(prompt).strip()[0].lower()
            except (EOFError,KeyboardInterrupt):
                choice = 'q'
            if choice not in 'neq':
                print 'invalice option,try agin:'
            else:
                chosen = True
        if choice == 'q':done = True
        if choice == 'n':newuser()
        if choice == 'e':olduser()
if __name__ == '__main__':
    showmenu()
    
#集合类型 :集合对象时一组无序排列的可哈希的值,集合成员可以作为字典的键,集合没有索引,不能使用切片。也没有键
#集合分为两种类型:set可变集合:可以增加删除元素,不可以哈希,frozenset不可变集合:不可以改变
#1、创建集合类型和赋值:集合只能使用set(),frozenset():工厂方法来创建
s1 = set('cheeseshop')
print s1   #set(['c', 'e', 'h', 'o', 'p', 's'])
s2 =frozenset('bookshop')
print s2     #frozenset(['b', 'h', 'k', 'o', 'p', 's'])
print type(s1)    #<type 'set'>
print type(s2)     #<type 'frozenset'>
print len(s1)           #6
print len(s1) == len(s2)   #True
print s1 == s2   #False
#2、访问集合中的值:可通过遍历查看集合成员或检查某个元素是否是一个集合中的成员
for value in s1 :print value
print 'c' in s1
#3、更新集合中的元素
s1.add('zx')   #set(['c', 'e', 'h', 'o', 'p', 's', 'zx'])
print s1
s1.update('zhaoyehong')
print s1    #set(['a', 'c', 'e', 'g', 'h', 'o', 'n', 'p', 's', 'zx', 'y', 'z'])
s1.remove('z')
print s1   #set(['a', 'c', 'e', 'g', 'h', 'o', 'n', 'p', 's', 'zx', 'y'])
s1 -= set('hong')
print s1        #set(['a', 'c', 'e', 'p', 's', 'zx', 'y'])
#4、删除集合中的成员和集合
del s1
#5、集合中的操作符
    #成员关系
s = set('cheeseship')
t = frozenset('bookshop')
print 'k' in s
print 'k ' in t #True
print 'c' not in t  #True
    #集合中的等价/不等价:两个集合相等是指:对每个集合而言,当且仅当其中的一个集合中的每个成员同时也是另一个集合中的成员
print s == t  #False
print s != t   #True
u = frozenset(s)
print s == u  #True
print set('posh') == set('shop')  #True
    #子集和超集:子集 < <=,超集:> >=
print set('shop') < set('cheeseshop')
print set('bookshop') > set('shop')
    #集合类型操作符
s = set('cheeseship')
t = frozenset('bookshop')
print s|t   #联合,并集:set(['c', 'b', 'e', 'i', 'h', 'k', 'o', 'p', 's'])
print s &t  #交集:set(['h', 's', 'p'])
print s - t  #补集/相对差集:set(['i', 'c', 'e'])
print s ^ t  #对分差集:set(['b', 'e', 'i', 'k', 'c', 'o'])
    #内建函数len(),set() frozenset()


TAG:

 

评分:0

我来说两句

日历

« 2024-05-01  
   1234
567891011
12131415161718
19202122232425
262728293031 

数据统计

  • 访问量: 15393
  • 日志数: 25
  • 建立时间: 2013-07-27
  • 更新时间: 2013-10-22

RSS订阅

Open Toolbar