Python five pit, 80% of you do not know (right, you know a five reached the general level)

1 yuan group containing a single element

Some functions in Python argument types as tuples, within which there is an element, which is created is wrong:

c = (5) # NO!

It actually creates a cosmetic element 5, a must to add after the element 逗号:

c = (5,) # YES!

2 default parameter is set to null

Contains the default function arguments, if the type of container and set to null:

def f(a,b=[]):  # NO!
    print(b)
    return b

ret = f(1)
ret.append(1)
ret.append(2)
# 当再调用f(1)时,预计打印为 []
f(1)
# 但是却为 [1,2]

This is the pit default parameters of the variable type, be sure to set the parameters of such default is None:

def f(a,b=None): # YES!
    pass

3 shared variables unbound Pit

Sometimes you want more than one function to share a global variable, but it is trying to modify local variables within a function:

i = 1
def f():
    i+=1 #NO!
    
def g():
    print(i)

It should be displayed in the f function is declared ias global variables:

i = 1
def f():
    global i # YES!
    i+=1

4 copy of the list of fast pit

In python *with a list of actions to achieve rapid replication elements:

a = [1,3,5] * 3 # [1,3,5,1,3,5,1,3,5]
a[0] = 10 # [10, 2, 3, 1, 2, 3, 1, 2, 3]

If the list elements such as lists or dictionaries composite type:

a = [[1,3,5],[2,4]] * 3 # [[1, 3, 5], [2, 4], [1, 3, 5], [2, 4], [1, 3, 5], [2, 4]]

a[0][0] = 10 #

The results may surprise you, others a[1[0], also be modified to 10

[[10, 3, 5], [2, 4], [10, 3, 5], [2, 4], [10, 3, 5], [2, 4]]

* This is because the compound is a pale reference to the copied object, i.e. id (a [0]) and id (a [2]) are equal house number. If you want to achieve the effect of deep copy, do the following:

a = [[] for _ in range(3)]

5 list of deleted pit

Delete elements in a list, this element may be repeated several times in the list:

def del_item(lst,e):
    return [lst.remove(i) for i in e if i==e] # NO!

Consider deleting this sequence elements [1,3,3,3,5] 3, wherein only two deleted found:

del_item([1,3,3,3,5],3) # 结果:[1,3,5]

The right approach:

def del_item(lst,e):
    d = dict(zip(range(len(lst)),lst)) # YES! 构造字典
    return [v for k,v in d.items() if v!=e]

These are the five common pit, hoping to see friends here can avoid these pits.

Published 65 original articles · won praise 0 · Views 564

Guess you like

Origin blog.csdn.net/weixin_46089319/article/details/103971566