List.append/扩展+操作员和+=

2024-04-26 21:56:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我很难理解下面代码的行为。在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]

Tags: and代码self示例列表foodefanother
2条回答

如果希望a_list保持为[[0]],而不管another)list中的第一个值发生了什么,为什么不将其初始化为__init__中的[[0]]?你知道吗

def __init__(self):
    self.a_list = [[0]]
    self.another_list = [0]
    # End of __init__; nothing else

使用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的元素,因此稍后的编辑会更改该对象的内容是很自然的。你知道吗

相关问题 更多 >