簡體   English   中英

Class 實例變量在 Python 中彈出不同列表時減少

[英]Class instance variable is reduced when popping a different list in Python

我正在嘗試來自 freecodecamp 的概率計算器,可以在這里找到

在 class function 到隨機 select 列表中的 n 個項目中,我通過self.contents訪問列表的內容,這是一個實例變量,用於填充任何帽子。 我的 function 看起來像這樣:

def draw(self,num_balls_drawn):
  randomlist = []
  templist = self.contents
  if num_balls_drawn <= len(templist):
    for x in range(num_balls_drawn):
      popped = templist.pop(random.randint(0, len(templist)-1)) # random has been imported
      randomlist.append(popped)
    return randomlist 

  else:
    return self.contents #If you ask for more items than there are in list, just returns list

因此,當我使用以下代碼創建 class 實例時:

class Hat:
  def __init__(self,**kwargs):
    self.__dict__.update(kwargs)
    contents=[]
    for key in self.__dict__:
      for x in range(self.__dict__.get(key)):
        contents.append(key)
    self.contents= contents

然后用hat = Hat(blue=4, red=2, green=6)創建一個實例,然后用print(hat.contents) print(hat.draw(7)) print(hat.contents) print(hat.draw(7))測試我的函數print(hat.contents) print(hat.draw(7)) print(hat.contents) print(hat.draw(7))

我希望得到一個列表['blue', 'blue', 'blue', 'blue', 'red', 'red', 'green', 'green', 'green', 'green', 'green', 'green']用於hat.contents和一個列表,例如['blue', 'blue', 'red', 'green', 'blue', 'blue', 'green']用於hat.draw(7)

然而,在第二次嘗試使用這些語句時,我卻返回['blue', 'blue', 'green', 'green', 'green']['blue', 'blue', 'green', 'green', 'green']

兩者的長度都只有 5。

盡管設置了一個臨時列表templist ,但每次我從templist中彈出一個項目時,我的self.contents仍然會縮短。

如果有人可以為我的問題提供解決方案,將不勝感激。

您的代碼的問題是 self.contents 是按地址而不是按值傳遞的。 您可以做的是將templist = self.contents更改為templist = self.contents[:] 新的抽獎 function 如下:

def draw(self,num_balls_drawn):
  randomlist = []
  templist = self.contents[:]
  if num_balls_drawn <= len(templist):
    for x in range(num_balls_drawn):
      popped = templist.pop(random.randint(0, len(templist)-1)) # random has been imported
      randomlist.append(popped)
    return randomlist 

  else:
    return self.contents #If you ask for more items than there are in list, just returns list

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM