[英]Iteratively add elements to a list
I am trying to add elements of a list in Python and thereby generate a list of lists. 我试图在Python中添加列表的元素,从而生成列表的列表。 Suppose I have two lists a = [1,2]
and b = [3,4,5]
. 假设我有两个列表a = [1,2]
和b = [3,4,5]
。 How can I construct the following list: 如何构建以下列表:
c = [[1,2,3],[1,2,4],[1,2,5]] ?
In my futile attempts to generate c
, I stumbled on an erroneous preconception of Python which I would like to describe in the following. 在我徒劳地尝试生成c
,我偶然发现了一个错误的Python观念,下面将对此进行描述。 I would be grateful for someone elaborating a bit on the conceptual question posed at the end of the paragraph. 有人对本段末尾提出的概念性问题有所阐述,我将不胜感激。 I tried (among other things) to generate c
as follows: 我试图(除其他外)生成c
,如下所示:
c = []
for i in b:
temp = a
temp.extend([i])
c += [temp]
What puzzled me was that a
seems to be overwritten by temp. 使我感到困惑的是, a
似乎已被温度覆盖。 Why does this happen? 为什么会这样? It seems that the =
operator is used in the mathematical sense by Python but not as an assignment (in the sense of := in mathematics). Python似乎在数学意义上使用了=
运算符,但未将其用作赋值(在数学中以:=表示)。
You are not creating a copy; 您不是要创建副本。 temp = a
merely makes temp
reference the same list object. temp = a
只是使temp
引用相同的列表对象。 As a result, temp.extend([i])
extends the same list object a
references : 结果, temp.extend([i])
扩展a
引用的相同列表对象 :
>>> a = []
>>> temp = a
>>> temp.extend(['foo', 'bar'])
>>> a
['foo', 'bar']
>>> temp is a
True
You can build c
with a list comprehension: 您可以使用列表理解来构建c
:
c = [a + [i] for i in b]
By concatenating instead of extending, you create a new list object each iteration. 通过串联而不是扩展,您可以在每次迭代中创建一个新的列表对象。
You could instead also have made an actual copy of a
with: 你可以代替也取得的实际拷贝a
具有:
temp = a[:]
where the identity slice (slicing from beginning to end) creates a new list containing a shallow copy. 身份切片(从头到尾切片)将创建一个包含浅表副本的新列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.