【问题标题】:Modifying a list within a list in Python [duplicate]在Python中修改列表中的列表[重复]
【发布时间】:2017-08-06 22:50:46
【问题描述】:

我正在尝试修改临时列表并将临时列表存储在可能的列表中,但我需要让 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)

【问题讨论】:

标签: python list


【解决方案1】:

为了将list1 的数组复制到temp,因为list1 是二维数组,正如其他人建议的那样,我们可以使用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')。并且正如上面在 cmets 中提到的,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)

【讨论】:

    猜你喜欢
    • 2016-10-26
    • 2011-03-11
    • 2017-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-05
    • 1970-01-01
    • 2012-12-20
    相关资源
    最近更新 更多