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]( )
- Python Cookbook Notes Chapter1
- Reading Notes for AngularJS -- Chapter1
- Python Cookbook
- python CookBook
- Python-cookbook
- CHAPTER1 INTRODUCTION -- Deep Learning Book Reading notes
- PRML Notes-Chapter1 Introduction(1.2 Probability Theory)
- Beginning Python Chapter1
- Chapter1 基础部分 - iOS 8 Swift Programming cookBook 读书笔记
- python核心编程笔记chapter1
- Python Notes
- Python notes
- Python Notes
- python notes
- Python notes
- Python Notes
- Python Notes
- Python Notes
- ArcGIS影像数据库的建立与入库 (转)
- 影像数据入ArcSDE空间数据库的方法与步骤
- platform设备驱动之按键扫描(misc设备)
- Ubuntu 11下 Ralink RT3592无线网卡
- I will come to you
- Python Cookbook Notes Chapter1
- platform设备驱动之LED(misc设备)
- 蛋疼的触摸屏调试经历
- mac下的免费UML建模工具
- HashMap
- wince下的进程相关操作
- iPhone开发--之 异常
- INF ClassInstall32 Section详解
- (2)stm32开发之使用Keil MDK以及标准外设库创建STM32工程