1. for循环遍历字典元素
d={'x':1,'y':2}print d for key,value in d: print key,'corresponds to', value Traceback (most recent call last): File "/Users/shuweizhang/Desktop/python scripts/dict/src/dict/__init__.py", line 3, in{'y': 2, 'x': 1} for key,value in d:ValueError: need more than 1 value to unpack
将d改为d.items()
y corresponds to 2x corresponds to 1
2. 并行迭代zip()
names=['anne','jack','ross','allen']age=[12,22,45,21]for key, value in zip(names,age): print key, '\'s age is ' , value anne 's age is 12jack 's age is 22ross 's age is 45allen 's age is 21
其中zip(names,age)将两个list压缩成一个含元组的列表:[('anne', 12), ('jack', 22), ('ross', 45), ('allen', 21)]
3. 按索引迭代enumerate()
假设在一个字符串列表中我们要替换所有包含'oss'的子字符串为'none'
首先写了如下一段code,但是输出结果却没有替换正确,didn't see why?
index = 0 names=['jack','ross','poss','asewoss']for name in names: if 'oss' in name: names[index]='none' index +=1print names['none', 'none', 'none', 'asewoss']
使用enumerate()迭代索引-键值对
index = 0 names=['jack','ross','poss','asewoss']for index,value in enumerate(names): if 'oss' in value: names[index]='none'print names['jack', 'none', 'none', 'none']
4. while True/break
先来看这样一个例子:
name = 'dummy'while name: name = raw_input('please enter your name: ') print 'your name is %s ' %name break
code开始处我们给name赋了一个值,应该避免这么做。
while True: name = raw_input('please enter your name: ') if not name: break print 'your name is %s ' %name
while True 提供了一个永远不会自己停止的循环,而在循环内部可通过if/break来终止循环。
5. 循环中的else,
我们见过了break跳出循环后做某事,但是怎么在循环没有跳出之前做某事呢?
while True: name = raw_input('please enter your name: ') if name: print 'your name is %s ' %name break else: print 'no name entered'
6. 列表推导式(list comprehension)
将名字首字母相同的男孩女孩整理出来:
girls=['dennis','jacy','rose']boys=['donald','jack','ryan']print [b+'+'+g for b in boys for g in girls if b[0]==g[0]]['donald+dennis', 'jack+jacy', 'ryan+rose']
7. exec和eval
exec 用于执行字符串中的代码,eval用于计算字符串中的表达式。但是这样带来潜在威胁,例如我们如果执行
from math import sqrt exec "sqrt = 1 "print sqrt(4) print sqrt(4)TypeError: 'int' object is not callable
外部代码覆盖了系统sqrt函数,造成其不可用
如何避免?我们可以增加一个namespace, 用以在其中存贮sqrt和1这一对键值,这样sqrt=1只在这个namespace中有效,也可以只在这个namespace中进行计算。
from math import sqrt scope={}exec "sqrt = 1 " in scopeprint sqrt(4)print scope['sqrt']print eval ('sqrt+5',scope)2.016