21. 判断一个文件是否存在
>>> import os.path
>>> os.path.isfile('find_string.sh')
True
>>> os.path.isfile('zm')
False
22. enum使用
>>> class Numbers:
... (one, two, three) = range(3)
...
>>> Numbers.one
0
23. 合并两个字典
>>> x = {'a':1, 'b':2}
>>> y = {'b':10, 'c':11}
>>> z = dict(x.items() + y.items())
>>> z
{'a': 1, 'c': 11, 'b': 10}
注意:
键b
的值会被第二个字典的值覆盖
24. 用字典的值对字典进行排序
对字典进行排序是不可能的,只有把字典转换成另一种方式才能排序.字典本身是无序的,但是像列表元组等其他类型是有序的.所以你需要用一个元组列表来表示排序的字典.
>>> import operator
>>> x = {1:2, 3:4, 4:3, 2:1, 0:0}
>>> sorted_x = sorted(x.items(), key=operator.itemgetter(1))
>>> sorted_x
[(0, 0), (2, 1), (1, 2), (4, 3), (3, 4)]
如果想要用键来进行排序:
>>> sorted_y = sorted(x.items(), key=operator.itemgetter(0))
>>> sorted_y
[(0, 0), (1, 2), (2, 1), (3, 4), (4, 3)]
25. 在一个函数里使用全局变量
如果我在一个函数里建了一个全局变量,那么我怎么在另一个函数里使用这个全局变量?
我需要把这个全局变量赋值给这个函数的局部变量吗?
如果你要在别的函数里使用全局变量,只要在被调用全局变量的函数里事先用global
声明一下:
>>> globvar = 0
>>> def set_globvar_to_one():
... global globvar
... globvar = 1
...
>>> def print_globvar():
... print globvar
...
>>> set_globvar_to_one()
>>> print_globvar()
1
我猜正是因为全局变量比较危险,所以Python为了确保你真的知道它是全局变量,所以需要加一个
global
关键字.