经过for循环后计数器变量未更改
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了经过for循环后计数器变量未更改相关的知识,希望对你有一定的参考价值。
我是Python的初学者,我正在研究一个问题,我希望计数器变量每次经过for循环时都减少一。它显示在这里。
overall_triangle = """75
95 64
17 47 82
18 35 87 10
20 04 82 47 65
19 01 23 75 03 34
88 02 77 73 07 63 67
99 65 04 28 06 16 70 92
41 41 26 56 83 40 80 70 33
41 48 72 33 47 32 37 16 94 29
53 71 44 65 25 43 91 52 97 51 14
70 11 33 28 77 73 17 78 39 68 17 57
91 71 52 38 17 14 91 43 58 50 27 29 48
63 66 04 68 89 53 67 30 73 16 69 87 40 31
04 62 98 27 23 09 70 98 73 93 38 53 60 04 23"""
overall_triangle_2d = [i.split() for i in overall_triangle.split('
')]
for i in range(0, len(overall_triangle_2d)):
for j in range(0, len(overall_triangle_2d[i])):
overall_triangle_2d[i][j] = int(overall_triangle_2d[i][j])
counter = 13
greatest_sum = []
for i in range(0, len(overall_triangle_2d[counter])):
print(counter)
num_1 = int(overall_triangle_2d[counter][i]) + int(overall_triangle_2d[counter + 1][i])
# print(num_1)
num_2 = int(overall_triangle_2d[counter][i]) + int(overall_triangle_2d[counter + 1][i + 1])
# print(num_2)
empty = []
if num_1 > num_2:
greatest_sum.append(num_1)
elif num_1 == num_2:
greatest_sum.append(num_1)
else:
greatest_sum.append(num_2)
# print(greatest_sum)
if len(greatest_sum) == counter + 1:
# print(overall_triangle_2d[counter + 1])
overall_triangle_2d[counter + 1] = empty
# print(overall_triangle_2d[counter + 1])
# print(overall_triangle_2d[counter])
overall_triangle_2d[counter] = greatest_sum
# print(overall_triangle_2d[counter])
# print(counter)
if counter == 0:
print(greatest_sum)
break
else:
greatest_sum = []
counter = counter - 1
# print(counter)
else:
continue
每次通过计数器变量运行它都不会更改。请让我知道我可以做些什么。
答案
每次迭代都添加一个值(num_1或num_2)以列出great_sum,然后在递减计数器之前具有条件if len(greatest_sum) == counter + 1:
,因此必须先等待counter + 1迭代a,然后再让len(greatest_sum)== counter + 1 ,并且您的迭代范围是len(overall_triangle_2d [counter]),其值为counter + 1,因此如果if语句在上一次迭代中返回true,并且将计数器值减为12,您能否解释一下代码的目标是什么?
以上是关于经过for循环后计数器变量未更改的主要内容,如果未能解决你的问题,请参考以下文章
如何在 Java 中的 Iterable 的 for 循环中创建一个计数器并获取计数器变量的值