python核心编程第二版

python核心编程第二版:第七章--映射与集合类型

2016-08-08  本文已影响34人  Bioconductor

方法一

dict1 = {}
dict2 = {'name':'earth','port':80}
print dict1,dict2

结果

{} {'name': 'earth', 'port': 80}

方法二:用dict()

fdict = dict((['x',1],['y',2]))
print fdict

结果

{'y': 2, 'x': 1}

方法三;fromkeys()

ddict = {}.fromkeys(('x','y'),-1)
print ddict

结果

{'y': -1, 'x': -1}

例子

dict2 = {'name':'earth','port':80}
for key in dict2.keys():
    print 'key = %s,value=%s' % (key,dict2[key])

结果

key = name,value=earth
key = port,value=80

关键词key具有唯一性,vlaue不具有

in and not in
返回True and False

例子

dict2 = {'name':'earth','port':80}
dict2['name'] = 'venus'
dict2['port'] = 6969
dict2['arch'] = 'sunos5'
print dict2

结果

{'arch': 'sunos5', 'name': 'venus', 'port': 6969}

例子

dict2 = {'name':'earth','port':80}
del dict2['name']
print dict2

结果

{'port': 80}

例子

dict2 = {'name':'earth','port':80}
dict2.clear()
print dict2

结果

{}
dict2 = {'name':'earth','port':80}
del dict2
print dict2

结果

Traceback (most recent call last):
  File "E:/workp/python/zx/test.py", line 11, in <module>
    print dict2
NameError: name 'dict2' is not defined

例子

dict2 = {'name':'earth','port':80}
dict2.pop('name')
print dict2

结果

{'port': 80}

比较大小

例子

dict4 = {'abc':123}
dict5 = {'abc':456}
print dict4 < dict5

结果

True

例子

dict5 = {'abc':456}
dict6 = {'aef':456}
print dict5 < dict6

结果

True

解释:

字典

例子

print dict(zip(('x','y'),(1,2)))

print dict([['x',1],['y',2]])

print dict([('xy'[i-1],i) for i in range(1,3)])

结果

{'y': 2, 'x': 1}
{'y': 2, 'x': 1}
{'y': 2, 'x': 1}

例子

dict8=dict(x=1,y=2)
print  dict8.copy()

结果

{'y': 2, 'x': 1}
len

dict8=dict(x=1)
dict2 ={'name':'earth','port':80}
print len(dict8),len(dict2)

返回键值对的数目

例子

def olduser():
    name = raw_input('login: ')
    pwd = raw_input('passwd: ')
    passwd = db.get(name) #得到设置的密码
    if passwd == pwd:
        pass
    else:
        print 'login incorrect'
        return

    print 'welcome back', name

例子

s = set('cheeseshop')
print s
t = frozenset('bookshop')
print t

结果

set(['c', 'e', 'h', 'o', 'p', 's'])
frozenset(['b', 'h', 'k', 'o', 'p', 's'])

上一篇 下一篇

猜你喜欢

热点阅读