从另一个列表的元素创建新列表,并引用后者的元素 [英] Creating a new list from elements of an other list, referencing the elements of the latter
问题描述
我想从上一个元素创建一个新列表,但不复制它们.就是这样:
I want to create a new list from a previous one's elements, but without copying them. That is what happens:
In [23]: list = range(10)
In [24]: list2 = list[0:4]
In [25]: list
Out[25]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [26]: list2
Out[26]: [0, 1, 2, 3]
尽管列表中的元素似乎具有相同的ID,
Though the elements of the lists seem to have the same id,
In [29]: id(list[1])
Out[29]: 145137840
In [30]: id(list2[1])
Out[30]: 145137840
在编辑一个元素之后,我不会更改所引用的对象,而是列表中该站点的值.
After editing one element, I don't change the object that is referenced, but the value for that site on the list.
In [31]: list[1] = 100
In [32]: id(list[1])
Out[32]: 145138628
In [33]: id(list2[1])
Out[33]: 145137840
In [34]: list
Out[34]: [0, 100, 2, 3, 4, 5, 6, 7, 8, 9]
In [35]: list2
Out[35]: [0, 1, 2, 3]
我想使用list2作为list某些特定元素的代表.我想应该有一个很好的方法来组成一个列表,当我也更改list的值时,它使我有机会编辑list元素的值.
I want to use the list2 as a representative of some particular elements of list. I'm guessing that there should be a good way to compose a list that gives me the chance to edit the values of the elements of list, when I also change the value for list.
推荐答案
变量中的任何地方 1
或另一个小数字,它始终具有相同的ID.这些数字仅存在一次,并且由于它们是不可变的,因此在任何地方都可以安全地引用它们.
Anywhere 1
or another small number is in a variable, it will always have the same id. These numbers only exist once, and since they're immutable, it's safe for them to be referenced everywhere.
使用切片语法 [:]
始终进行复制.
Using slice syntax [:]
always makes a copy.
设置 list1 [1]
时,您没有更改存储在内存中的值,而是将 list1 [1]
指向新位置在记忆中.因此,由于您没有将 list2 [1]
指向其他位置,因此它仍然指向旧位置和值.
When you set list1[1]
, you're not changing the value of what's stored in memory, you're pointing list1[1]
to a new location in memory. So since you didn't point list2[1]
to a different location, it still points to the old location and value.
请不要命名变量 list
,因为该名称具有内置函数.
Never name a variable list
since there is a built in function by that name.
如果您想通过最小的修改来完成您正在谈论的事情,请尝试:
If you want to do what you're talking about with minimal modification, try:
list1 = [[x] for x in range(10)]
list2 = list1[:4]
list1[1][0] = 100
print list2
您只需要始终在要引用的项目之后添加[0].由于列表不会被替换,因此只是其中的项目,而 list2
指向列表而不是项目,它将保持同步.
You just need to always add [0] after the item you want to reference. As the lists don't get replaced, just the item in them, and list2
points to the list not the item, it will stay in sync.
这篇关于从另一个列表的元素创建新列表,并引用后者的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!