<2026年6月>
31123456
78910111213
14151617181920
21222324252627
2829301234
567891011

统计

  • 随笔 - 0
  • 文章 - 1
  • 评论 - 0
  • 引用 - 0

常用链接

留言簿

文章分类

文章档案

搜索

  •  

最新评论

Python Cookbook Notes Chapter1

1.2 Swapping Values Without Using aTemporary Variable

利用元组赋值的特性:a, b, c = b, c, a

Tuples are often surrounded withparentheses, as in (b, c, a), but the parentheses are not necessary, exceptwhere the commas would otherwise have some other meaning (e.g., in a functioncall). The commas are what create a tuple, by packing the values that are thetuple's items.

1.3 Constructing a Dictionary WithoutExcessive Quoting

利用python的可变参数:*args  **kwds

*args是一个list**kwds是一个dict,如果两个一起出现,那么**kwds必须在最后,其余有名称的变量必须在最前

1.4 Getting a Value from a Dictionary

使用d.get(‘key’, ‘not found’)来解决,第二个参数未指定时,返回None

1.5 Adding an Entry to a Dictionary

使用somedict.setdefault(somekey, []).append(somevalue)来解决。

enrymutable的时候setdefault函数很有用,它令d[key]=value,然后返回value

entryimmutable的时候,setdefault则不是很有用

1.6 Associating Multiple Values with EachKey in a Dictionary

有两种方法:

1 d1 = {}
2 d1.setdefault(key,[]).append(value)
3 d2 = {}
4 d2.setdefault(key,{})[value] = 1

 

第一种不会自动去重,第二种可以自动去除重复的元素。

1.7 Dispatching Using a Dictionary

利用字典,实现其他语言中switchcaseselect的作用。 1 animals = []

 2 number_of_felines = 0
 3 def deal_with_a_cat( ):
 4    global number_of_felines
 5    print "meow"
 6    animals.append('feline')
 7    number_of_felines += 1
 8 def deal_with_a_dog( ):
 9    print "bark"
10    animals.append('canine')
11 def deal_with_a_bear( ):
12    print "watch out for the *HUG*!"
13    animals.append('ursine')
14 tokenDict = {
15    "cat": deal_with_a_cat,
16    "dog": deal_with_a_dog,
17    "bear": deal_with_a_bear,
18 }
19 # Simulate, say, somewords read from a file
20 words = ["cat","bear""cat""dog"]
21 for word in words:
22    # Look up the function to call for each word, then call it
23    functionToCall = tokenDict[word]
24    functionToCall( )
25    # You could also do it in one step, tokenDict[word]( )


posted on 2012-04-27 21:27 Andimeo 阅读(80) 评论(0)  编辑 收藏 引用 所属分类: Python


只有注册用户登录后才能发表评论。
网站导航:   博客园   博客园最新博文   博问   管理