简体   繁体   English

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

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

I want to add the last three items of the list "M.Carte" (length 40) in the list "self.CarteInMano", using a while loop: 我想使用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

But, after: 但是之后:

M1=Mano(1)
M1.Pesca()

I get: 我得到:

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

Why "Pesca" doesn't do what it has to do? 为什么“ Pesca”没有做它必须做的事情?

Your issue is here: 您的问题在这里:

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

this will only run when a == 3 you should try this instead: 这仅在a == 3时运行,而应尝试以下操作:

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

The reason is that in the first code a will only run when it is EQUAL to dimensioni, and since it start at 0 and not 3 it will never be equal, and skips the code. 原因是,在第一个代码中,a仅在与Dimensioni相等时才运行,并且由于它从0开始而不是从3开始,所以它将永远不相等,并跳过该代码。 If you use <= instead, you now run the code while a is less than or equal to 3 如果使用<=代替,则现在在a小于或等于3时运行代码

NOTE 注意

If you want to get 3 elements, then use just < instead, using <= will get you 4 elements (since it works for 0, 1, 2, and 3). 如果要获得3个元素,则仅使用<而使用<=将获得4个元素(因为它适用于0、1、2和3)。

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

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