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)来解决。
当enry是mutable的时候setdefault函数很有用,它令d[key]=value,然后返回value。
当entry是immutable的时候,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
利用字典,实现其他语言中switch、case或select的作用。 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]( )