[英]Stop the function from changing the original list
我正在使用 pygame 制作一個帶有挑戰的賓果游戲……問題是我得到了一個函數“challengeGeneretor”和原始挑戰列表,其中 len 為 35 個項目,在我使用該函數后,它從原始列表中刪除,而不是從列表中刪除我在函數中制作(我之前沒有嘗試過)並且當我嘗試為賓果游戲生成新的隨機挑戰時會出錯。 (它適用於第一次生成)
這是功能:
def challengesGeneretor(self, challenges, board):
challenges1 = challenges
for n, i in enumerate(board):
for j in range(len(i)):
x = random.randint(0, len(challenges1) - 1)
board[n][j] = challenges1[x]
challenges1.remove(challenges1[x])
challenges1 = challenges # just me trying things
return board
和事件功能......不知道它是否是問題的一部分
def playing_events(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
self.running = False
if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
selected = self.mouseOnGrid()
buttonClick = self.mouseOnButton()
if selected:
self.selected.add(selected)
if buttonClick:
self.selected = set()
self.grid = testboard # "testboard" = empty board
self.grid = self.challengesGeneretor(challenges, testboard)
這里的錯誤:
Traceback (most recent call last):
File "/main.py", line 5, in <module>
app.run()
File "\app_class.py", line 25, in run
self.playing_events()
File "\pygames\app_class.py", line 47, in playing_events
self.grid = self.challengesGeneretor(challenges, testboard)
File "\app_class.py", line 146, in challengesGeneretor
x = random.randint(0, len(challenges1) - 1)
File "\random.py", line 222, in randint
return self.randrange(a, b+1)
File "\random.py", line 200, in randrange
raise ValueError("empty range for randrange() (%d,%d, %d)" % (istart, istop, width))
ValueError: empty range for randrange() (0,0, 0)
任何幫助將不勝感激,謝謝!
我想你需要了解淺拷貝的原理。 參考
而且您可能想問問自己是否真的想制作一份副本,因為當列表變大時,性能可能是一個問題。
challenges1 = challenges
不會在內存中創建新數組,而是將內存地址傳遞給新變量(檢查指針)。 它與復雜的數據結構(如數組)的工作方式類似。
如果您想要原始列表的副本,請創建一個創建空列表的函數,並將原始列表的元素復制到新創建的列表中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.