python 编程中要注意的事情

来源:互联网 发布:网络征文比赛2017 编辑:程序博客网 时间:2024/05/21 12:47

记住python中那些非常简单的事

a, b = b, aa= [1,2,3,4,5]>>>a[::2][1,3,5]一个特殊的例子 x[::-1]用来反转x

不要用可变对象作为默认参数值(Don’t use mutable as defaults)

def function(x, l=[]):      # 不要这么干def function(x, l=None):    # 更好的一种方式    if l is None:       l = []

这是因为函数的默认值实在函数定义的时候实例化的,不是在函数调用的时候。
但是,默认值类型是可变变量的时候才会出现这种情况。
例:

def foo(numbers=[]):    numbers.append(9)    print numbers>>> foo() # first time, like before[9]>>> foo() # second time[9, 9]>>> foo() # third time...[9, 9, 9]>>> foo() # WHAT IS THIS BLACK MAGIC?![9, 9, 9, 9]#因为每次都是调用的默认值,所以默认值改变>>> foo()[9]>>> foo(numbers=[1,2])[1, 2, 9]>>> foo(numbers=[1,2,3])[1, 2, 3, 9]#重写默认值,所以不会出现上面的问题def foo(count=0):    count += 1    print count10>>> foo()1>>> foo()1>>> foo(2)3>>> foo(3)4>>> foo()1#这是因为整型是个不可变变量,所以默认值始终不会改变,不会出现上面的问题。def print_now(now=time.time()):    print now23456>>> print_now()1373121487.91>>> print_now()1373121487.91>>> print_now()1373121487.91#它是在函数定义时计算的,所以无论调用多少次都不会变。

使用iteritems而不是items

d = {1: "1", 2: "2", 3: "3"}for key, val in d.items()       # 调用items()后会构建一个完整的list对象for key, val in d.iteritems()   # 只有在迭代时每请求一次才生成一个值

使用isinstance 而不是type

不要这样做:

if type(s) == type(""): ...if type(seq) == list or \    type(seq) == tuple: ...

应该是这样:

if isinstance(s, basestring): ...if isinstance(seq, (list, tuple)): ...

学习各种集合(learn the various collections)
python有各种各样的容器数据类型,在特定情况下选择python内建的容器如:list和dict。通常更多像如下方式使用:

  freqs = {}  for c in "abracadabra":      try:          freqs[c] += 1      except:          freqs[c] = 1

一种更好的方案如下:

freqs = {}   for c in "abracadabra":       freqs[c] = freqs.get(c, 0) + 1

一种更好的选择 collection类型defautdict:

from collections import defaultdictfreqs = defaultdict(int)    for c in "abracadabra":        freqs[c] += 1

当创建类时Python的魔术方法:

  __eq__(self, other)      # 定义相等操作的行为, ==.  __ne__(self, other)      # 定义不相等操作的行为, !=.  __lt__(self, other)      #定义小于操作的行为, <.  __gt__(self, other)      #定义不大于操作的行为, >.  __le__(self, other)      #定义小于等于操作的行为, <=.  __ge__(self, other)      #定义大于等于操作的行为, >=.

条件赋值重点内容
表达式请起来恰恰像:如果y等于1就把3赋值给x,否则把2赋值给x,当然同样可以使用链式条件赋值如果你还有更复杂的条件的话。

(x = 3 if (y == 1) else 2 if (y == -1) else 1

然而到了某个特定的点,它就有点儿过分了。

记住,你可以在任何表达式中使用if-else例如:

c1 if y == 1 else func2)(arg1, arg2)

func1将被调用如果y等于1的话,反之func2被调用。两种情况下,arg1和arg2两个参数都将附带在相应的函数中。

类似地,下面这个表达式同样是正确的

x = (class1 if y == 1 else class2)(arg1, arg2)

class1和class2是两个类

带有索引位置的集合遍历
遍历集合时如果需要使用到集合的索引位置时,直接对集合迭代是没有索引信息的,普通的方式使用:

colors = ['red', 'green', 'blue', 'yellow']for i in range(len(colors)):    print (i, '--->', colors[i])

应该用:

for i, color in enumerate(colors):    print (i, '--->', color)

字符串连接
字符串连接时,普通的方式可以用 + 操作:

names = ['raymond', 'rachel', 'matthew', 'roger',         'betty', 'melissa', 'judith', 'charlie']s = names[0]for name in names[1:]:    s += ', ' + nameprint (s)

应该用:

print (', '.join(names))