繁体   English   中英

在“ while”循环中“追加”不起作用,Python

[英]“Append” in a while loop not working, Python

我想使用while循环在列表“ self.CarteInMano”中添加列表“ M.Carte”(长度40)的最后三项:

class Mano:
    def __init__(self,Giocatore,Dimensioni=3):
        self.Giocatore=Giocatore
        self.CarteInMano=[]
        self.Dimensioni=Dimensioni

    def Pesca(self):
        a=0
        while a==self.Dimensioni:
            self.CarteInMano.append(M.Carte.pop())
            a=a+1

但是之后:

M1=Mano(1)
M1.Pesca()

我得到:

len(M.Carte)
40
len(M1.CarteInMano)
0

为什么“ Pesca”没有做它必须做的事情?

您的问题在这里:

while a==self.Dimensioni:
    self.CarteInMano.append(M.Carte.pop())
    a=a+1

这仅在a == 3时运行,而应尝试以下操作:

while a<=self.Dimensioni:
    self.CarteInMano.append(M.Carte.pop())
    a=a+1

原因是,在第一个代码中,a仅在与Dimensioni相等时才运行,并且由于它从0开始而不是从3开始,所以它将永远不相等,并跳过该代码。 如果使用<=代替,则现在在a小于或等于3时运行代码

注意

如果要获得3个元素,则仅使用<而使用<=将获得4个元素(因为它适用于0、1、2和3)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM