https://www.sololearn.com/en/compiler-playground/cmz9Q7PhQ2s8
리스트를 객체 전달고 append하면 의도하지 않게 모든 원소가 바뀌는 문제
2018년에 파이썬 공부할 때 처음에 많이 당황한다는 이 문제를 긴 고민 끝에 해결했는데
솔로런에서 옛날 코드를 보고 기록용으로 코드를 올리고,
5년이 지난 지금 나는 어떻게 해결할 것인지 코드를 짜 보려고 한다.
일단 과거 코드-해외 사이트라 안되는 영어로 이상하게 써 놨다. (GPT가 없었다...)
코드도 읽다보니 대체 이게 뭔가 싶다.
포문 인덱스는 왜 저런거며 왜 append할 리스트를 외부에서 선언을 하며;;
'''
====================
LIST IN LIST PROBLEM
====================
bigger_list.append(list) works like
[[list]]
[[list],[list]]
[[list],[list],[list]]
[[list],[list],[list],[list]]
'''
# This is the problem.
from random import randint
list_elmt = [0, 0, 0]
list_out =[]
for i in range(1, 5):
for n in range (3):
list_elmt [n] = randint(0,9)
list_out.append(list_elmt)
print(list_out)
# Solved it by using Messinger.
list_elmt = [0, 0, 0]
list_out =[]
for i in range(1, 5):
for n in range (3):
list_elmt [n] = randint(0,9)
messenger = []
for elmt in list_elmt:
messenger.append(elmt)
list_out.append(messenger)
print(list_out)
# Solved it by using list()
list_elmt = [0, 0, 0]
list_out =[]
for i in range(1, 5):
for n in range (3):
list_elmt [n] = randint(0,9)
list_out.append(list(list_elmt))
print(list_out)
지금이라면 이렇게 할 거다.
from random import randint
list_out: list[list[int]] = [[randint(0, 9) for _ in range(3)] for _ in range(4)]
print(list_out)
끝.