У меня проблема с созданием двухмерного массива - PullRequest
0 голосов
/ 04 августа 2020

Я определил функцию, которая изменяет список (в основном перемещает последний элемент в начало списка), а затем я попытался создать 2-й список с этой функцией.

Вот код:

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 раза, каждый возврат в списке совпадает с последним значением ( print внутри функции используется для отладки).

Я буду очень рад, если мне кто-то поможет :)

1 Ответ

0 голосов
/ 04 августа 2020

Вам нужно делать копию списка каждый раз, когда он передается в функцию nextRow (см. Код ниже). Дополнительная информация здесь (связанные топи c).

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]]
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...