【问题标题】:Why Python while loop is reseting a local variable counter?为什么 Python while 循环正在重置局部变量计数器?
【发布时间】:2017-06-23 10:13:10
【问题描述】:

它总是返回重复值示例:

{
    "0": [4886, 7051, 9612, 9613, 4895],
    "1": [4886, 7051, 9612, 9613, 4895],
    "2": [4886, 7051, 9612, 9613, 4895],
    "3": [4886, 7051, 9612, 9613, 4895],
    "4": [4886, 7051, 9612, 9613, 4895]
}

我不知道为什么计数器在嵌套循环结束时重置。它应该在每批中添加下一个产品,而不是从头开始。请告诉我如何解决它?谢谢!

counter = 0
max_number = 4
batches = {}
batch = [] 
batch_counter = 0
while batch_counter <= max_number:
    while counter <= max_number:
        batch.append(data[counter])
        counter = counter+1

    batches[batch_counter] = batch
    batch_counter = batch_counter+1

batches = json.dumps(batches)
return HttpResponse(batches)

【问题讨论】:

  • 你能给个样品data吗?
  • 这是它返回的内容:{"0": [4886, 7051, 9612, 9613, 4895], "1": [4886, 7051, 9612, 9613, 4895], "2" : [4886, 7051, 9612, 9613, 4895], "3": [4886, 7051, 9612, 9613, 4895], "4": [4886, 7051, 9612, 9613, 4895]} 但我想补充下一个喜欢:{"0": [4886, 7051, 9612, 9613, 4895], "1": [next ids], "3": [next ids}
  • “计数器重置”是什么意思?除了第一行之外,您的代码中没有任何行将 counter 变量设置为零。

标签: python json python-2.7 python-3.x dictionary


【解决方案1】:

在内部循环中设置 batch 变量后,您不会重置它。

while batch_counter <= max_number:
    batch = []
    while counter <= max_number:
        ...

在您的代码中,您使用列表初始化批处理一次。相同的列表用于添加元素batch.append(data[counter])。这个列表也是每次添加batches[batch_counter] = batch

【讨论】:

  • 现在它返回给我这样的 json 对象:{"0": [4886, 7051, 9612, 9613, 4895], "1": [], "2": [], "3 ": [], "4": []}
  • 这是因为您正在循环内部循环中的所有元素:while counter &lt;= max_number:。尝试将 max_number 更改为每个列表中所需的元素数。如果您希望每个列表中有 1 个,则可以完全删除循环。
  • 我明白了。感谢您的帮助:)
【解决方案2】:

这不起作用的原因是 batch 在第一次迭代之后保持不变。一旦构建了第一个batch 列表,counter 就不会再次设置为0。结果,内部while 循环永远不会再次执行。这对 Python 来说不是问题,因为您从未指示 Python 删除 batch 列表。所以它会简单地采用旧的,并在第二次、第三次等迭代中添加那个。

您可以通过counter 设置为0 并再次将batch 设为新的空列表来解决问题,例如:

counter = 0
max_number = 4
batches = {}
batch = [] 
batch_counter = 0
while batch_counter <= max_number:
    counter = 0
    batch = []
    while counter <= max_number:
        batch.append(data[counter])
        counter = counter+1

    batches[batch_counter] = batch
    batch_counter = batch_counter+1

batches = json.dumps(batches)
return HttpResponse(batches)

不过,你可以让事情变得更优雅:

max_number1 = max_number+1
batch = {i : data[max_number1*i:max_number1*(i+1)] for i in range(max_number1)}
batches = json.dumps(batches)
return HttpResponse(batches)

替换整个代码片段。

【讨论】:

    【解决方案3】:

    因为您的计数器达到了 max_number(内部循环),这就是为什么内部循环只执行一次,在跳过该内部循环并且您在 'batches' 中设置相同的 'batch' 之后。

    【讨论】:

    • 添加后:while ...:batch = [] while..... 它返回给我这样的 json 对象:{"0": [4886, 7051, 9612, 9613, 4895 ]、“1”:[]、“2”:[]、“3”:[]、“4”:[]}
    • 您还应该为内循环使用不同的计数器并在内循环执行后重置,然后您的程序应该可以工作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-05
    相关资源
    最近更新 更多