python学习11-集合和字典

来源:互联网 发布:知名网络集成商有哪些? 编辑:程序博客网 时间:2024/06/11 08:16

集合:创立的一组无序,但是所有元素只出现一次的元素集合

ten=set(range(10))lows=set([0,1,2,3,4])odds=set([1,3,5,7,9])lows.add(9)              #在lows后面加上9lows.difference(odds)    #lows减去oddslows.issubset(ten)      #lows是ten的子集?答案是truelows.issuperset(odds)    #答案是false,判断一个自己包含另一个子集否?lows.remove(0)            #移除第一个元素lows.symmetric_difference(odds)   #根据不再两个集合中的元素创立新的集合lows.union(odds)                    #根据两个集合中所有元素,创建一个新的集合lows.clear()                      #清楚所有元素lows

注意用set()来设置值!

2.散列表hash

hash(123)  #123hash('good')   #-753937853hash('ture')

值得注意的是:散列码是通过对值得计算得到,所以,当某列表内容发生变化的时候,其散列码也会发生相应的变化。正因为这样,python只允许集合含有不变量。
当然,布尔值、数字、字符串和数组也是可以应用的。

3.字典

#字典就是给一个索引,对应一个值,如同电话簿,给名字对应一个号码,因此提供查询功能birds={'canada goose':3,'northern fulmar':11,'chinese monkey':55}   #定义了一个字典birds#birds#birds['canada goose']           #输出3#注意如果字典中没有,就会报错,如同数组越界错误一样。#if 'canada goose'  in birds:   #用来查询是否在字典中#    print "have"#else#    print "donnot have!"#在字典中删除某个条目,用del d[k]"""del birds['canada goose']birds"""#x循环for x in birds:    print x,birds[x]       #这里可以看出,列表的x是数值,而字典的x是键值,并且他的输出是无序的,并非从第一个到最后一个#字典的内置函数scientists={'Newton':1642,'Darwin':1809,'Turing':1912}print 'keys:',scientists.keys()         #输出键值,如Newton,Darwin,Turingprint 'values',scientists.values()      #键值对应的值print 'items',scientists.items()        #输出键值和对应的值print 'get',scientists.get('Curie',1867)    #查找字典中Curie对应的值,如果没有默认为1867temp={'Curie':1867,'Hopper':1906,'Franklin':1920}scientists.update(temp)              #将temp加入到scitists的字典里面print "after update:",scientistsscientists.clear()                     #清除字典里面的数print 'after clear:',scientists#输出结果为:"""northern fulmar 11chinese monkey 55canada goose 3keys: ['Turing', 'Newton', 'Darwin']values [1912, 1642, 1809]items [('Turing', 1912), ('Newton', 1642), ('Darwin', 1809)]get 1867after update: {'Curie': 1867, 'Darwin': 1809, 'Franklin': 1920, 'Turing': 1912, 'Newton': 1642, 'Hopper': 1906}after clear: {}"""
0 0
原创粉丝点击