4

我在 python 中有一个包含 2 个大小相同的列表的列表,例如:

list_of_lists = [list1, list2]

在对list1和进行一些处理后的 for 循环中list2,我必须交换它们,以便list1成为list2list2成为初始化为全零的列表。所以在迭代结束时 list_of_lists 必须看起来像:

list_of_lists = [list1 which has contents of list2, list2 which has all zeros]

在 C 中,可以只复制 的指针,list2然后list1指向list2一个初始化为全零的列表。我如何在 python 中做到这一点?

4

3 回答 3

9

听起来你主要是在循环list1中工作。list2所以你可以重新分配它们的值:

list1 = list2
list2 = [0]*len(list2)

Python 还允许您将其缩短为单行:

list1, list2 = list2, [0]*len(list2)

但在这种情况下,我发现两行版本更具可读性。或者,如果你真的想要list_of_lists,那么:

list_of_lists = [list2, [0]*len(list2)]

或者如果你想要两者:

list1, list2 = list_of_lists = [list2, [0]*len(list2)]
于 2013-01-02T04:39:47.780 回答
1

像这样...

list_of_lists = [list_of_lists[1], []]

for i in range(count):
    list_of_lists[1].append(0)
于 2013-01-02T04:40:41.180 回答
1
list_of_lists=[ list_of_lists[1], [0,]*len(list_of_lists[1]) ]

交换的成本与您提到的指针交换相同

于 2013-01-02T05:08:30.127 回答