from http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html#more-about-tuples

交换值

其他语言中交换两个变量的值一般是这样的:

1
2
3
tmp = a;
a = b;
b = tmp;

python则可以这样:

b, a = a, b

还可以这样用:

1
2
3
4
l =['David', 'Pythonista', '+1-514-555-1234']
name, title, phone = l
print name, title, phone
# output: David Pythonista +1-514-555-1234

_

下划线在python命令行的使用:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
>>> 2
2
>>> _
2
>>> 'Hello'
'Hello'
>>> _
'Hello'
>>> None
>>> _
'Hello'

由以上示例可以看出 _ 储存着上一次printed的结果

注意:如果上一次返回值为 None, _ 不会改变

in

Good:

1
2
for key in d:
    print key

Bad:

1
2
for key in d.keys():
	print key

改变字典时,才要用到 d.keys():

1
2
for key in d.keys():
    d[str(key)] = d[key]

key in dict, 而不是 dict.has_key():

1
2
3
4
5
6
7
# do this:
if key in d:
    ...do something with d[key]

# not this:
if d.has_key(key):
    ...do something with d[key]

合并两个list为一个dict

1
2
3
4
5
6
given = ['John', 'Eric', 'Terry', 'Michael']
family = ['Cleese', 'Idle', 'Gilliam', 'Palin']
pythons = dict(zip(given, family))
print pythons
# output: 
# {'Eric': 'Idle', 'John': 'Cleese', 'Michael': 'Palin', 'Terry': 'Gilliam'}