在Python中关联两个list / dict项(更改一个的值会修改另一个)

时间:2016-03-03 00:27:44

标签: python list pointers dictionary

在Python中,是否可以将列表/字典中的两个项关联起来,以便一个值的值更改会触发另一个项的修改?

例如,我有一个列表:

# Python example
# item_one = 'item_one'
# item_two = 'item_one'
list_with_associated_items = [item_one, item_two]
list_with_associated_items[0] = 'item_two'
# that's it, the value of list_with_associated_items[1] should turn to
# 'item_two' now.

那么,list / dict的结构需要使list_with_associated_items [1]的值变成'item_two'呢?

我可以使用C语言中的指针来实现这样的目标,例如:

/* C example */
char buffer[40] = 'associated_item';
char *item_one_pointer = buffer;
char *item_two_pointer = buffer;
char *associated_list[2] = [item_one_pointer, item_two_pointer];
/* Change the content of item one */
strcpy(associated_list[0], 'item_one');
printf('%s\n', associated_list[1]);
/* The printing result will be 'item_one', which means the second
   item has been modified because it is "associated" with item
   one (sharing the same memory) */

Python中是否有类似的技术?非常感谢。

1 个答案:

答案 0 :(得分:0)

是的,可以将两个(或更多)变量名绑定到同一个对象。

A = [1,2,3]
B = A
B[1] = 42
print(A)           # prints: [1,42,3]

C = [A, B]
C[0][1] = 9
print(A, B)        # prints: [1,9,3] [1,9,3]
print(C[0], C[1])  # prints: [1,9,3] [1,9,3]

只要A,B,C [0]和C [1]都绑定(想想指向)相同的列表。更改列表元素会更改所有绑定。

但是:B = ['a', 'b']将B绑定到新列表。它不会更改旧列表。所以:

B = ['a', 'b']
print(A, B)        # prints: [1,9,3] ['a','b']

这有点像这两个C语句之间的区别:

item_two_pointer[1] = 'Z';
item_two_pointer = another_buffer;