Error encountered a collection of python

A mistake, for string in list with the remove, resulting in no traversing a complete list:

Error codes are as follows:

for string in str_list:
    if string == word:
        str_list.remove(string)

 

Error Second, there is more than one layer of the list, with a shallow copy

Error codes are as follows:

a = [[1]]
b = a.copy()  # 浅拷贝
b[0][0] = 2   #这时修改 b 的值,a 的值也会改变

With this package need to copy

import copy

a = [[1]]
b = copy.deepcopy(a)
b[0][0] = 2           #这时再修改list的内容,a的内容不会跟着变了

 

Error 3, misuse list initialization

Because [[]] * 9 equivalent to copy a list of nine times, the right way to generate a two-dimensional list is as follows:

list = [[] for i in range(9)]

 

Published 45 original articles · won praise 1 · views 3378

Guess you like

Origin blog.csdn.net/qq_22498427/article/details/104453886