Python Cookbook Notes Chapter1

来源:互联网 发布:盛势网络剧百度云资源 编辑:程序博客网 时间:2024/05/24 03:43

1.2 Swapping Values Without Using aTemporary Variable

利用元组赋值的特性:

a, b, c = b, c, a

Tuples are often surrounded with parentheses, 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’)
使用get来解决,第二个参数未指定时,返回None

1.5 Adding an Entry to a Dictionary

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

当enry是mutable的时候setdefault函数很有用,它令d[key]=value,然后返回value。

当entry是immutable的时候,setdefault则不是很有用

1.6 Associating Multiple Values with EachKey in a Dictionary

有两种方法:

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

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

1.7 Dispatching Using a Dictionary

利用字典,实现其他语言中switch、case或select的作用。

animals = []number_of_felines = 0def deal_with_a_cat( ):        global number_of_felines        print "meow"        animals.append('feline')        number_of_felines += 1def deal_with_a_dog( ):        print "bark"        animals.append('canine')def deal_with_a_bear( ):        print "watch out for the *HUG*!"        animals.append('ursine')tokenDict = {        "cat": deal_with_a_cat,        "dog": deal_with_a_dog,        "bear": deal_with_a_bear,}# Simulate, say, some words read from a filewords = ["cat", "bear", "cat", "dog"]for word in words:# Look up the function to call for each word, then call it        functionToCall = tokenDict[word]        functionToCall( )        # You could also do it in one step, tokenDict[word]( )

原创粉丝点击