在Python中修改列表中的列表

时间:2017-03-15 23:27:41

标签: python list

我试图修改临时列表并将临时列表存储在可能的列表中,但我需要将list1保持不变。当我通过Python运行时,我的临时列表没有改变,所以我想知道这出错了。

list1 = [['1', '1', '1'],
     ['0', '0', '0'],
     ['2', '2', '2']]

temp = list1
possible = []

for i in range(len(temp)-1):
    if(temp[i][0] == 1):
            if(temp[i+1][0] == 0):
                    temp[i+1][0] == 1

possible = possible + temp
temp = list1

print(possible)

1 个答案:

答案 0 :(得分:0)

为了将list1的数组复制到templist1是2D数组,正如其他人所建议的那样,我们可以使用deepcopy。请参阅this link here.。或者,可以使用列表理解以及显示here来完成。

数组以string为元素,因此条件语句if(temp[i][0] == 1)if(temp[i+1][0] == 0)可以替换为if(temp[i][0] == '1')if(temp[i+1][0] == '0')。如上所述,评论temp[i+1][0] == 1必须由temp[i+1][0] = 1取代。您可以尝试以下操作:

from copy import deepcopy

list1 = [['1', '1', '1'],
         ['0', '0', '0'],
         ['2', '2', '2']]

# copying element from list1
temp = deepcopy(list1)
possible = []
for i in range(len(temp)-1):
    if(temp[i][0] == '1'):
        if(temp[i+1][0] == '0'):
            temp[i+1][0] = '1'


possible = possible + temp

print('Contents of possible: ', possible)
print('Contents of list1: ', list1)
print('Contents of temp: ', temp)
相关问题