Python - While-Loop直到列表为空

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39934635/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 22:56:19  来源:igfitidea点击:

Python - While-Loop until list is empty

python

提问by Adam Starrh

I'm working with Django and I have a queryset of objects that has been converted to a list (unpaid_sales). I'm executing a process that iterates through this list and operates on each item until either the list is empty, or a given integer (bucket) reaches zero.

我正在使用 Django,并且我有一个已转换为列表 ( unpaid_sales) 的对象查询集。我正在执行一个过程,该过程遍历此列表并对每个项目进行操作,直到列表为空或给定的整数 ( bucket) 达到零为止。

This is how I set it up:

我是这样设置的:

while unpaid_sales:
    while bucket > 0:
        unpaid_sale = unpaid_sales.pop(0)
        ...do stuff

In some cases, I am getting the following error:

在某些情况下,我收到以下错误:

pop from empty list

从空列表中弹出

What's wrong with my logic?

我的逻辑有什么问题?

采纳答案by tynn

Your end criteria must be formulated a little differently: loop while there are items and the bucketis positive. oris not the right operation here.

您的最终标准必须略有不同:循环时有项目并且bucket是正数。or在这里不是正确的操作。

while unpaid_sales and bucket > 0
    unpaid_sale = unpaid_sales.pop(0)
    #do stuff

回答by MMF

Do not use separate whileloops. Do as follows :

不要使用单独的while循环。执行以下操作:

while unpaid_sales and bucket > 0 :
    unpaid_sale = unpaid_sales.pop(0)
    ...do stuff

回答by Efferalgan

You should do a single loop: while bucket>0 and unpaid_sales. Here, you are popping elements in the bucketloop, and then just just check that bucketis positive, but you do not check that element_salesstill has elements in it.

你应该做一个循环:while bucket>0 and unpaid_sales。在这里,您在bucket循环中弹出元素,然后只检查它bucket是否为正,但不检查其中是否element_sales仍有元素。