python foundation pit in common

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:
[Python]  plain text view  Copy the code
?
1
c = (5) # NO!
It actually creates a cosmetic element 5, you must add a comma after the element:
[Python]  plain text view  Copy the code
?
1
c = (5,) # YES!

2 default parameter is set to null

Contains the default function arguments, if the type of container and set to null:
[Python]  plain text view  Copy the code
?
01
02
03
04
05
06
07
08
09
10
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:
[Python]  plain text view  Copy the code
?
1
2
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:
[Python]  plain text view  Copy the code
?
1
2
3
4
5
6
i = 1
def f():
    i+=1 #NO!
     
def g():
    print(i)
It should be displayed in the function declaration f i as global variables:
[Python]  plain text view  Copy the code
?
1
2
3
4
i = 1
def f():
    global i # YES!
    i+=1

4 copy of the list of fast pit

* In python and a list of actions to achieve rapid replication elements:
[Python]  plain text view  Copy the code
?
1
2
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:
[Python]  plain text view  Copy the code
?
1
2
3
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, a other [1 [0] 10, also be modified
[Python]  plain text view  Copy the code
?
1
[[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:
[Python]  plain text view  Copy the code
?
1
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:
[Python]  plain text view  Copy the code
?
1
2
3
4
5
def del_item(lst,e):
    return [lst.remove(i) for i in e if i==e] # NO!
考虑删除这个序列[1,3,3,3,5]中的元素3,结果发现只删除其中两个:
 
del_item([1,3,3,3,5],3) # 结果:[1,3,5]
The right approach:
[Python]  plain text view  Copy the code
?
1
2
3
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 157 original articles · won praise 43 · views 90000 +

Guess you like

Origin blog.csdn.net/qq_39581763/article/details/104213307