我很难理解下面代码的行为。在python 3.6中
下面的示例代码是我实际代码的抽象。我这样做是为了更好地描述我的问题。我正在尝试将一个列表添加到另一个列表中。产生一个二维列表。为了核对会员资格,以后再核对名单。尽管我无法按我喜欢的方式添加我的列表
a_list = []
another_list = [7,2,1]
a_list.DONT_KNOW(another_list)
another_list = [7,3,1]
结果:
a_list
[[7,2,1]]
another_list
[7,3,1]
我的问题示例:
class foo:
def __init__(self):
self.a_list = []
self.another_list = [0]
####### Modifying .extend/.append##############
self.a_list.append(self.another_list) # .append() | .extend(). | extend([])
###############################################
def bar(self):
######## Modifying operator########
self.another_list[0] += 1 # += | +
###################################
print('a_list = {} another_list = {} '.format(self.a_list, self.another_list))
def call_bar(f, repeats):
x = repeats
while x > 0:
x -= 1
foo.bar(f)
f = foo()
call_bar(f,3)
重复5次。修改列表.函数和增量运算符。输出:
# .append() and +=
a_list = [[1]] another_list = [1]
a_list = [[2]] another_list = [2]
a_list = [[3]] another_list = [3]
# .extend() and +=
a_list = [0] another_list = [1]
a_list = [0] another_list = [2]
a_list = [0] another_list = [3]
# .append() and +
a_list = [[1]] another_list = [1]
a_list = [[2]] another_list = [2]
a_list = [[3]] another_list = [3]
#.extend() and +
a_list = [0] another_list = [1]
a_list = [0] another_list = [2]
a_list = [0] another_list = [3]
#.extend([]) and +
a_list = [[1]] another_list = [1]
a_list = [[2]] another_list = [2]
a_list = [[3]] another_list = [3]
注意,在所有这些例子中,当我得到二维数组时(我需要)。当操作另一个列表时,列表中的值会改变。我如何获得代码来执行此操作?你知道吗
#SOME METHOD I DON'T KNOW
a_list = [[0]] another_list = [1]
a_list = [[0]] another_list = [2]
a_list = [[0]] another_list = [3]
如果希望
a_list
保持为[[0]]
,而不管another)list
中的第一个值发生了什么,为什么不将其初始化为__init__
中的[[0]]
?你知道吗使用
append
,添加一个another_list
的引用作为a_list
的第一个元素。使用extend
,将another_list
元素的引用添加到a_list
。你知道吗必须使用
self.a_list.append(self.another_list.copy())
创建another_list
的快照,然后将其添加到a_list
。您的代码实际上添加了another_list
作为a_list
的元素,因此稍后的编辑会更改该对象的内容是很自然的。你知道吗相关问题 更多 >
编程相关推荐