【问题标题】:I have a problem with creating 2 dimensional array我在创建二维数组时遇到问题
【发布时间】:2020-08-04 15:53:09
【问题描述】:

我定义了一个改变列表的函数(基本上将最后一项移动到列表的开头),然后我尝试用这个函数制作一个二维列表。

这里有一些代码:

prevRow = ["blue", "yellow", "red", "black", "white"]
def nextRow():
    prevRow.insert((0, prevRow.pop()))
    print(prevRow)
    return  prevRow
tablePreset = [["blue", "yellow", "red", "black", "white"], nextRow(), nextRow(), nextRow(), nextRow()]
print(tablePreset)
prevRow = ["blue", "yellow", "red", "black", "white"]
tablePreset = [["blue", "yellow", "red", "black", "white"]]
def nextRow():
    prevRow.insert((0, prevRow.pop()))
    print(prevRow)
    return  prevRow
for _ in range(4):
    tablePreset.append(nextRow())
print(tablePreset)

在这两种情况下我都得到了

['white', 'blue', 'yellow', 'red', 'black']
['black', 'white', 'blue', 'yellow', 'red']
['red', 'black', 'white', 'blue', 'yellow']
['yellow', 'red', 'black', 'white', 'blue']
[['blue', 'yellow', 'red', 'black', 'white'], ['yellow', 'red', 'black', 'white', 'blue'], ['yellow', 'red', 'black', 'white', 'blue'], ['yellow', 'red', 'black', 'white', 'blue'], ['yellow', 'red', 'black', 'white', 'blue']]

我不知道为什么,但即使我调用了 4 次函数,列表中的每个返回值都与最后一个值相同(函数内的打印用于调试目的)。

如果有人帮助我,我会非常高兴:)

【问题讨论】:

    标签: python-3.x list multidimensional-array


    【解决方案1】:

    每次将列表传递给函数nextRow 时,您都需要对其进行复制(参见下面的代码)。更多信息here(相关主题)。

    prevRow = ["blue", "yellow", "red", "black", "white"]
    tablePreset = [["blue", "yellow", "red", "black", "white"]]
    
    def nextRow(prevRow):
        prevRow_copy = prevRow.copy()
        prevRow_copy.insert(0, prevRow_copy.pop())
        return prevRow_copy
    
    for _ in range(4):
        prevRow = nextRow(prevRow)
        tablePreset.append(prevRow)
        
    print(tablePreset)
    
    # >> out:
    # [['blue', 'yellow', 'red', 'black', 'white'],
    #  ['white', 'blue', 'yellow', 'red', 'black'],
    #  ['black', 'white', 'blue', 'yellow', 'red'],
    #  ['red', 'black', 'white', 'blue', 'yellow'],
    #  ['yellow', 'red', 'black', 'white', 'blue']]
    

    另一个说明文案重要性的小例子:

    a = []
    b = [1,2,3]
    
    a.append(b)
    b.pop()
    a.append(b)
    b.pop()
    a.append(b)
    
    print(a)
    
    # >> out:
    # [[1], [1], [1]]
    
    a = []
    b = [1,2,3]
    
    a.append(b.copy())
    b.pop()
    a.append(b.copy())
    b.pop()
    a.append(b.copy())
    
    print(a)
    
    # >> out:
    # [[1, 2, 3], [1, 2], [1]]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-25
      • 2014-01-25
      • 2021-12-29
      • 2021-12-17
      相关资源
      最近更新 更多