简体   繁体   English

For 循环更改原始列表变量

[英]For loop changes original list variable

Quick question from someone with limited Python experience.来自 Python 经验有限的人的快速提问。 So I have some lists inside a list.所以我在列表中有一些列表。 I want to iterate through it, append something to each iteration, and then store that in a different list.我想遍历它,在每次迭代中附加一些内容,然后将其存储在不同的列表中。

For example:例如:

var=[[1],[2],[3]]
var2 = []

for item in var:
    var2.append(item.append("x"))

However, rather than the expected output for var2 of [[1, 'x'], [2, 'x'], [3, 'x']] I get [None, None, None]然而,不是[[1, 'x'], [2, 'x'], [3, 'x']] var2的预期输出,我得到[None, None, None]

I was planning to reuse my original variable, var , for a different purpose.我打算重用我的原始变量var ,用于不同的目的。 However, var is now equal to [[1, 'x'], [2, 'x'], [3, 'x']]然而, var现在等于[[1, 'x'], [2, 'x'], [3, 'x']]

What is going on here?这里发生了什么?

The append function modifies its input. append函数修改其输入。 So when you call item.append(...) , you are modifying item , which is a reference to one of the elements in var .因此,当您调用item.append(...) ,您正在修改item ,它是对var元素之一的引用。

You can minimally reproduce this via您可以通过

var=[[1],[2],[3]]

for item in var:
    item.append("x")

In addition, the return value of append is None , so you're effectively calling var2.append(None) for each item, explaining your var2 result.此外, append的返回值是None ,因此您有效地为每个项目调用var2.append(None) ,解释您的var2结果。

To avoid this, use a non-destructive method that returns the value you want, such as为避免这种情况,请使用返回所需值的非破坏性方法,例如

var=[[1],[2],[3]]
var2 = []

for item in var:
    var2.append(item + ["x"])

Or, better still,或者,更好的是,

var=[[1],[2],[3]]
var2 = [item + ["x"] for item in var]

If you refer to the docs list.append as well as others return None and that's what you're appending.如果您参考文档list.append以及其他人返回None这就是您要附加的内容。 Therefore you need to concatenate or extend the list while returning the value.因此,您需要在返回值时连接或扩展列表。 I suggest using item + ['x'] so your loop would look as follows:我建议使用item + ['x']以便您的循环如下所示:

for item in var:
    var2.append(item + ['x'])

Although why not just use a list comprehension for this?尽管为什么不为此使用列表理解?

var=[[1],[2],[3]]
var2 = [item + ['x'] for item in var]

Results:结果:

[[1, 'x'], [2, 'x'], [3, 'x']]

Your for loop is the culprit.你的 for 循环是罪魁祸首。 This is not that hard but we have to make sure what is going on in the nested list appends.这并不难,但我们必须确保嵌套列表追加中发生了什么。

My solution to this would be:我对此的解决方案是:

var=[[1],[2],[3]]
var2 = []

for i in range(len(var)):
  list = []
  list.append(var[i][0])
  list.append('x')
  var2.append(list)

print(var)
print(var2)
>>> [[1], [2], [3]]
>>> [[1, 'x'], [2, 'x'], [3, 'x']]

Even though it may be intuitive to write:尽管写起来可能很直观:

for list in var:
  list.append('x')
  var2.append(newList)

This will change the values in the lists in the original var list as well.这也将更改原始var列表中列表中的值。

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

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