简体   繁体   English

通过迭代列表追加项目

[英]Appending Items by Iterating list

I've designed a following function that takes a list as a parameter and returns another list. 我设计了以下函数,该函数将列表作为参数并返回另一个列表。

def function(list):
    A = []
    B = []
    for num in list:
        A.append(num)
        B.append(A)
    return B

In this function, I assumed that the function would append A to A depending on the current state of A. Working under that assumption. 在此函数中,我假定该函数将根据A的当前状态将A追加到A。在该假设下工作。 I called the function 我叫这个功能

>>> test([1,2,3,4,5])

expected the output to be 预期输出为

[[1], [1, 2], [1, 2, 3], [1, 2, 3, 4], [1, 2, 3, 4, 5]]

However, the result that I get is 但是,我得到的结果是

[[1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5]]

Why is this? 为什么是这样? Is there any solution around this problem? 有没有解决这个问题的办法?

You need to copy it by value. 您需要按值复制它。 In your current situation, you are passing by reference. 在当前情况下,您正在通过引用。 Hence, every index gets updated as A changes. 因此,每个索引都会随着A变化而更新。 Should be: 应该:

    B.append(A[:])

Notice the [:] for copying by value. 请注意[:]用于按值复制。

To clarify, running your code here we can examine the result of calling function on [1,2] : 为了澄清, 在这里运行您的代码,我们可以检查在[1,2]上调用function的结果:

小马扎尔戈在看着。

Now, consider what happens when we make a copy: 现在,考虑当我们制作副本时会发生什么:

def function(list):
    A = []
    B = []
    for num in list:
        A.append(num)
        B.append(A[:])
    return B

print function([1,2])

3份,以全部统治。

Also, as a side note: you should change the names of your variables. 另外,作为一个补充说明:您应该更改变量的名称。 For example, by declaring the parameter as list you shadow the list method. 例如,通过将参数声明为list可以隐藏list方法。

You can append the copy of A to B to avoid using the same reference of A : 您可以将A的副本附加到B以避免使用与A相同的引用:

for num in list:
      A.append(num)
      B.append(A[:])

Lists are passed by reference. 列表通过引用传递。 To copy them use the syntax B.append(A[:]) 要复制它们,请使用语法B.append(A[:])

def function(list):
    A = []
    B = []
    for num in list:
        A.append(num)
        B.append(A[:])
    return B

In your code you sending reference instead of data. 在您的代码中,您发送引用而不是数据。

Working code 工作代码

def function(list):
   A = []
   B = []
   for num in list:
      A.append(num)
      B.append(A[:])
   return B

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM