简体   繁体   English

如何更改列表中的元素,并保留原始列表的副本?

[英]How do I change an element in a list, and keep a copy of the original list?

I've searched around and tried a lot of stuff but I can't get this to work. 我到处搜索并尝试了很多东西,但无法正常工作。 I think the problem is something to do with how Python list names point to the list, rather than being the actual list, but I still can't figure it out. 我认为这个问题是事做Python列表名称如何指向列表,而不是实际的名单,但我仍然无法弄清楚。 The situation is this (it's a list of dictionaries): 情况是这样的(这是词典列表):

list_original = [dictionary1, dictionary2, dictionary3]
dictionary2_modified = dictionarymodifier(dictionary2) #some function that modifies the chosen element
list_modified = [i for i in list_original] #makes copy of original list
for i,n in enumerate(dictionary_original):
    if i==1:
        list_modified[1] = dictionary2_modified #replaces element with modified version
return list_original, list_modified

And many similar things, but I always either get two of the original list or two of the new list! 和许多类似的事情一样,但我总是会得到两个原始列表或两个新列表! I add that I'm using python 2.4 and don't have a choice in that. 我补充说,我正在使用python 2.4,但没有选择。

Many thanks for any help 非常感谢您的帮助

Mutable vs. Immutable 可变与不可变

You need to know the difference between mutable and immutable elements. 您需要了解可变元素和不可变元素之间的区别。 Namely, both dictionaries and lists in Python are mutable . 即,Python中的字典和列表都是可变的 Which means that if you modify it in one place, it is also modified in the other place. 这意味着,如果您在一处修改它,那么它也会在另一处修改。

In addition, the variable of mutable type (like list or dict ) can contain immutable elements (eg. str ), as well as the other way around: variable of immutable type (eg. tuple ) can contain mutable elements (such as list or dict ). 此外,可变类型的变量(例如listdict )可以包含不可变元素(例如str ),也可以采用其他方式:可变类型的变量(例如tuple )可以包含可变元素(例如listdict )。

Example for mutability 可变性示例

So, this shows the mutability using the example of list: 因此,使用清单示例显示了可变性:

>>> a = [1, 2, 3, 4]
>>> b = a
>>> a
[1, 2, 3, 4]
>>> b
[1, 2, 3, 4]
>>> a[2] = 'x'
>>> a
[1, 2, 'x', 4]
>>> b
[1, 2, 'x', 4]

How to obtain a copy of list or dict 如何获取列表或字典的副本

To obtain a copy of list , you simply can do this instead: 要获取list的副本,您只需执行以下操作即可:

new_list = old_list[:]  # the slicing at the end just takes the whole list

In case of dict this is generally sufficient: 如果有dict ,通常就足够了:

new_dict = old_dict.copy()

Nested lists / dicts 嵌套列表/字典

However, although lists / dicts that are flat or contain only mutable elements, can be copied the way I showed, to obtain a copy of more complex mutable data structures you need to do something more... 但是,尽管列表/字典是平面的或仅包含可变元素,但是可以按照我所展示的方式进行复制,但要获得更复杂的可变数据结构的副本,您还需要做更多的事情...

In such case very helpful may be the copy module with its deepcopy function . 在这种情况下,具有deepcopy copy 功能copy模块可能会很有帮助。 Documentation of copy module says more about its purpose: copy模块的文档详细说明了其用途:

Assignment statements in Python do not copy objects, they create bindings between a target and an object. Python中的赋值语句不复制对象,它们在目标和对象之间创建绑定。 For collections that are mutable or contain mutable items, a copy is sometimes needed so one can change one copy without changing the other. 对于可变或包含可变项的集合,有时需要一个副本,因此一个副本可以更改一个副本而不更改另一个副本。 This module provides generic shallow and deep copy operations (explained below). 此模块提供通用的浅层和深层复制操作(在下面说明)。

Is your dictionarymodifier actually mutating dictionary2 in place? 是您的dictionarymodifier实际上变异dictionary2到位? If so, the way you build your list is irrelevant. 如果是这样,则建立列表的方式就无关紧要。

Simply using list_modified = list(list_original) works fine to create a shallow copy of the list, which you can then modify to your heart's content, but only if you don't modify the items in the original list (which you can't if they're immutable built-in things like numbers or strings, so beginners often mistake this for a deep copy). 只需用list_modified = list(list_original)工作正常创建列表,然后你就可以修改你的心脏的内容的拷贝,但只有当你不修改原始列表中的项目(可以不若它们是数字或字符串之类的内置属性,因此初学者经常将其误认为是深层副本)。

If you really need to copy the list, you can use copy.deepcopy to do so. 如果确实需要复制列表,则可以使用copy.deepcopy进行复制。

You need to create a copy of the list. 您需要创建列表的副本。

copy=list(original)
original[0] = None

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

相关问题 如何更改嵌套列表中的元素? - How do I change an element in a nested list? 设置列表后如何保留每个元素的原始索引 - How can I keep the original index of each element after setting a list 如何通过引用而不是按值复制列表的单个元素? - How do I copy a single element of a list by reference and not by value? 创建列表的副本,以使列表的每个元素都与原始元素不同? - Create a copy of a list such that each element of the list is different from the original? 如何使用用户输入更改列表元素? - How do I change the element of a list with user input? 如何在以原始顺序使用元素时访问列表中的所有其他元素? - How do I access every other element in a list while using the elements in the original order? 如何在python中的for循环中更改列表元素的值? - How do i change a list element's value in a for loop in python? 如何复制包含列表的 Pandas 数据框,以便将来对副本中列表的更改不会改变原始列表 - How can I copy a pandas dataframe that contains a list, so that future changes to the list in the copy will not alter the original one 如何在迭代中复制列表? - How do I copy a list in an iteration? 如何删除列表中集合最少的元素并只保留最多的元素? - How do I remove the element with fewest sets in a list and only keep the one with the most?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM