Welcome 微信登录
编程资源 图片资源库 蚂蚁家优选 PDF转换器

首页 / 操作系统 / Linux / Python中的字典应用实例

字典中的键使用时必须满足一下两个条件:1、每个键只能对应一个项,也就是说,一键对应多个值时不允许的(列表、元组和其他字典的容器对象除外)。当有键发生冲突时(即字典键重复赋值),取最后的赋值。>>> myuniversity_dict = {"name":"yuanyuan", "age":18, "age":19, "age":20, "schoolname":Chengdu, "schoolname":Xinxiang}
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name "Chengdu" is not defined
>>> myuniversity_dict = {"name":"yuanyuan", "age":18, "age":19, "age":20, "schoolname":"Chengdu", "schoolname":"Xinxiang"}
>>> myuniversity_dict
{"age": 20, "name": "yuanyuan", "schoolname": "Xinxiang"}
>>>2、键必须是可哈希的,像列表和字典这样的可变类型,由于他们是不可哈希的,所以不能作为字典的键。为什么呢?—— 解释器调用哈希函数,根据字典中键的值来计算存储你的数据的位置。如果键是可变对象,可以对键本身进行修改,那么当键发生变化时,哈希函数会映射到不同的地址来存储数据,这样哈希函数就不可能可靠地存储或获取相关的数据; 选择可哈希键的原因就是他们的值不能被改变。摘抄python 核心编程(第二版)的一个实例如下:#!/usr/bin/env pythondb = {}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("passwd: ")
    db[name] = pwddef olduser():
    name = raw_input("login: ")
    pwd = raw_input("passwd: ")    passwd = db.get(name)
    if passwd == pwd:
     print "welcome back", name
    else:
        print "login incorrect"def showmenu():
    prompt = """(N)ew User Login
(E)xisting User Login
(Q)uitEnter choice:"""
    done = False
    while not done:        chosen = False
        while not chosen:
            try:
             choice = raw_input(prompt).strip()[0].lower()
            except:
             choice = "q"
            print " You picked: [%s]" % choice
            if choice not in "neq":
             print "invalid option, try again"
            else:
             chosen = True        if choice == "q":done = True
        if choice == "n":newuser()
        if choice == "e":olduser()if __name__ == "__main__":
    showmenu()运行结果:[root@localhost src]# python usrpw.py
(N)ew User Login
(E)xisting User Login
(Q)uitEnter choice:nYou picked: [n]
login desired: root
passwd: 1
(N)ew User Login
(E)xisting User Login
(Q)uitEnter choice:nYou picked: [n]
login desired: root
name taken, try anotherOpenCV官方教程中文版(For Python) PDF  http://www.linuxidc.com/Linux/2015-08/121400.htmUbuntu Linux下安装OpenCV2.4.1所需包 http://www.linuxidc.com/Linux/2012-08/68184.htmUbuntu 12.04 安装 OpenCV2.4.2 http://www.linuxidc.com/Linux/2012-09/70158.htmCentOS下OpenCV无法读取视频文件 http://www.linuxidc.com/Linux/2011-07/39295.htmUbuntu 12.04下安装OpenCV 2.4.5总结 http://www.linuxidc.com/Linux/2013-06/86704.htmUbuntu 10.04中安装OpenCv2.1九步曲 http://www.linuxidc.com/Linux/2010-09/28678.htm基于QT和OpenCV的人脸识别系统 http://www.linuxidc.com/Linux/2011-11/47806.htm[翻译]Ubuntu 14.04, 13.10 下安装 OpenCV 2.4.9  http://www.linuxidc.com/Linux/2014-12/110045.htmOpenCV的详细介绍:请点这里
OpenCV的下载地址:请点这里本文永久更新链接地址:http://www.linuxidc.com/Linux/2016-08/133908.htm