URN Logo
UNIX Resources » Linux » China Linux Forum » Python 编 程 » 19 » [精华] Python 食谱--1.5:增加一个入口到字典里
announcement 声明: 本页内容为中国Linux论坛的内容镜像,文章的版权以及其他所有的相关权利属于中国Linux论坛和相应文章的作者,如果转载,请注明文章来源及相关版权信息。
Resources
China Linux Forum(finished)
Linux Forum(finished)
FreeBSD China(finished)
linuxforum.net
  业界新闻与评论
  自由软件杂谈
  IT 人生
  Linux软件快递
  翻译作坊
  Linux图书与评论
  GNU Emacs/XEmacs
  Linux 中文环境和中文化
  Linux桌面与办公软件
  Linux 多媒体与娱乐版
  自由之窗Mozilla
  笔记本电脑上的Linux
  Gentoo
  Debian 一族
  网络管理技术
  Linux 安装与入门
  WEB服务器和FTP服务器
  域名服务器和邮件服务器
  Linux防火墙和代理服务器应用
  文件及打印服务器
  技术培训与认证
  Linux内核技术
  Linux 嵌入技术
  Linux设备驱动程序
  Linux 集群技术
  LINUX平台数据库
  系统和网络安全
  CPU 与 编译器
  系统计算研究所专栏
  Linux下的GUI软件开发
  C/C++编程版
  PHP 技 术
  Java&jsp技术
  Shell编程技术
  Perl 编 程
  Python 编 程
  XML/Web Service 技术
  永远的Unix
  FreeBSD世界
   
[精华] Python 食谱--1.5:增加一个入口到字典里
Author: rings    Posted: 2004-04-24 23:46    Length: 4,149 byte(s)
[Original] [Print] [Top]
1.5 Adding an Entry to a Dictionary
增加一个入口到字典里

Credit: Alex Martelli

1.5.1 Problem
问题

Working with a dictionary D, you need to use the entry D[k] if it's already present, or add a new D[k] if k isn't yet a key in D.
用一个字典D工作,如果D[k]存在,使用它。如果不存在增加一个新的D[k]

1.5.2 Solution
解决

This is what the setdefault method of dictionary objects is for. Say we're building a word-to-page numbers index. A key piece of code might be:
这个是字典对象的setdefault方法所做的。 假定,我们构造一个词到页(word-to-page)的数字索引。关键的代码片断是这样的:

theIndex = {}
def addword(word, pagenumber):
if theIndex.has_key(word):
theIndex[word].append(pagenumber)
else:
theIndex[word] = [pagenumber]

Good Pythonic instincts suggest substituting this "look before you leap" pattern with an "easier to get permission" pattern (see Recipe 5.4 for a detailed discussion of these phrases):
良好的python本能建议用“轻松获得许可”(easier to get permission)模式来替换掉“三思而后行”(look before you leap)模式(这些过程的详细讨论请看Recipe 5.4)
【译注:“轻松获得许可”,即我们使用异常。这样就不用去检查变量。“三思而后行”就是说,每次我们都需要检查变量然后在根据检查的结果来做不同的处理】

def addword(word, pagenumber):
try: theIndex[word].append(pagenumber)
except AttributeError: theIndex[word] = [pagenumber]

This is just a minor simplification, but it satisfies the pattern of "use the entry if it is already present; otherwise, add a new entry." Here's how using setdefault simplifies this further:
这仅仅是一个次要的简化。但是它满足了“如果入口存在使用它,否则,增加新的入口”的模式。这里是怎么样使用setdefault来更进一步简化
def addword(word, pagenumber):
theIndex.setdefault(word, []).append(pagenumber)

1.5.3 Discussion
讨论

The setdefault method of a dictionary is a handy shortcut for this task that is especially useful when the new entry you want to add is mutable. Basically, dict.setdefault(k, v) is much like dict.get(k, v), except that if k is not a key in the dictionary, the setdefault method assigns dict[k]=v as a side effect, in addition to returning v. (get would just return v, without affecting dict in any way.) Therefore, setdefault is appropriate any time you have get-like needs but also want to produce this specific side effect on the dictionary.
对于这个任务, 字典的Setdefault方法是一个便利的捷径。尤其对你想增加的新入口是可变的这种情况非常有用。如果k不是字典里的键值,setdefault方法有dict[k]=v的作用,并且返回一个v(get方法只返回v,不以任何方式影响字典)。除此之外,基本上,dict.setdefault(k, v)更象dict.get(k, v)。

setdefault is particularly useful in a dictionary with values that are lists, as detailed in Recipe 1.6. The single most typical usage form for setdefault is:
当一个字典的值是list,setdefault是非常有用的,细节在Recipe 1.6。大多数典型的使用形式是:
somedict.setdefault(somekey, []).append(somevalue)

Note that setdefault is normally not very useful if the values are immutable. If you just want to count words, for example, something like the following is no use:
注意, 当值是不可变的时候,setdefault不是非常有用。如果你仅仅想计算单词,例如,象下面这些是不能使用的:
theIndex.setdefault(word, 1)

In this case, you want:
在这种情况下,你想:
theIndex[word] = 1 + theIndex.get(word, 0)

since you will be rebinding the dictionary entry at theIndex[word] anyway (because numbers are immutable).
因为你无论如何将重新绑定字典入口在theIndex[word]上。(因为数字是不可变的)

1.5.4 See Also
参考
Recipe 5.4; the Library Reference section on mapping types.
[Original] [Print] [Top]
« Previous thread
[精华] Python 食谱--1.6:在字典里把每一个键同多个值关联起来
Python 编 程
19
Next thread »
deallocating None ,这个错误是怎么的?
     

Copyright © 2007 UNIX Resources Network, All Rights Reserved.      About URN | Privacy & Legal | Help | Contact us
备案序号: 京ICP备05006143    webmaster: webmaster@unixresources.net
This page created on 2008-07-17 04:11:40, cost 0.049129009246826 ms.