簡體   English   中英

Python; 原始列表在函數內更改

[英]python; original list changing within function

在我的函數中,我需要將列表中元素的值更改為默認值(10)而不更改原始列表。

function(orig_list):

dup_list = list(orig_list)

#Setting the appropriate value for the list but don't want to change the original list. 
for i in dup_list:
    if dup_list[dup_list.index(i)][1] == 11 or dup_list[dup_list.index(i)][1] == 12 or dup_list[dup_list.index(i)][1] == 13:
        dup_list[dup_list.index(i)][1] = 10

但是,當我稍后在代碼中調用該函數並打印原始列表時,它也發生了變化。 我希望函數執行此操作並給我一個值但不更改原始列表。

有多種方法可以復制可變數據結構,例如列表和字典。 如果只有不可變成員,淺拷貝是有效的,但是如果列表中有一個列表,例如,你需要一個深拷貝。

為了顯示:

from copy import deepcopy

l = [1,['a', 'b', 'c'],3,4]
l2 = list(l)
l3 = l.copy()
l4 = deepcopy(l)


# Mutate original list
l[0] = 10  # All of the copies are unaffected by this.
l[1][0] = 'f' # All of the copies except for the deep copy are affected by mutating a mutable item inside the shallow copy of the list.

print(l, l2, l3, l4)

# Result:
# [10, ['f', 'b', 'c'], 3, 4] [1, ['f', 'b', 'c'], 3, 4] [1, ['f', 'b', 'c'], 3, 4] [1, ['a', 'b', 'c'], 3, 4]

如果不允許導入任何內容來深度復制列表,那么您可以使用簡單的遞歸函數自行完成。 我下面的示例假設您的列表僅包含不可變項(float、int、str、tuple 等)和相同的列表。 例如,它不會深度復制字典(但您可以添加):

old = [[1, 2,3], [3, 4,[2, 3, 4], 2, [1,2]]]


def deep_copy_list(inlist):
   results = []
   for item in inlist:
       if type(item) != list:     # item is not a list so just append to results
           results.append(item)
       else:
           results.append(deep_copy_list(item))  # item is a list so append a copy
   return results

new = deep_copy_list(old)

print("id of element 0 of old is", id(old[0]))
print("id of element 0 of new is", id(new[0]))

id of element 0 of old is 136833800
id of element 0 of new is 151480776

(打印語句僅顯示(例如)舊列表的元素 0 中的列表已被復制到具有新 id 值的新列表中。)

然后,一旦您擁有原始列表的深層副本的新列表,您就可以像以前的解決方案一樣修改原始列表

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM