[英]Python count up by 5 after each iteration in for loop
I am trying to open a csv file in python and read the rows into a list.我试图在 python 中打开一个 csv 文件并将行读入列表。
The list is then sent to a function where I want to add 5 to the value of x after each iteration with the value of d going up by 10 after every 10th iteration.然后将该列表发送到 function,我想在每次迭代后将 5 添加到 x 的值,每 10 次迭代后 d 的值增加 10。
d I have working but can't quite figure out x. d 我有工作但不能完全弄清楚 x。 Please can someone help me understand where I am going wrong with my math.
请有人帮助我了解我的数学哪里出了问题。 I thought setting x = 0 outside the loop and then x+=5 inside would do it.
我认为在循环外设置 x = 0 然后在循环内设置 x+=5 就可以了。
results = []
with open('file.csv', newline='') as inputfile:
for row in csv.reader(inputfile):
results.append(row[0]) # 24 rows in csv file
def buildcount(listGroup, z):
listGroup = listGroup
z = z
x = 0
for i in range (0, len(listGroup))
print(i)
d = 10*(i // 10 + z)
x +=5
print(x)
if i % 10 == 0:
x = 0
return i
z = 10
mainInput = results
buildcount(mainInput)
#current output of x
5
5
10
15
20
25
30
35
40
45
5
10
15
20
25
30
35
40
45
5
10
15
20
25
#desired output of x
0
5
10
15
20
25
30
35
40
45
0
5
10
15
20
25
30
35
40
45
0
5
10
15
It looks like you want x
to reset after 50 and then increment d after reaching multiples of ten.看起来您希望
x
在 50 之后重置,然后在达到 10 的倍数后递增 d。 This uses mod ( %
) for the first, and just integer division for the second.第一个使用 mod (
%
),第二个仅使用 integer 除法。
x = 0
d = 0
for i in range(21):
x = i*5 % 50
d = int(i/10) * 10
print(f'{i=} {x=} {d=}')
returns回报
i=0 x=0 d=0
i=1 x=5 d=0
i=2 x=10 d=0
i=3 x=15 d=0
i=4 x=20 d=0
i=5 x=25 d=0
i=6 x=30 d=0
i=7 x=35 d=0
i=8 x=40 d=0
i=9 x=45 d=0
i=10 x=0 d=10
i=11 x=5 d=10
i=12 x=10 d=10
i=13 x=15 d=10
i=14 x=20 d=10
i=15 x=25 d=10
i=16 x=30 d=10
i=17 x=35 d=10
i=18 x=40 d=10
i=19 x=45 d=10
i=20 x=0 d=20
It looks like you're looking for some fairly simple math on the loop counter:看起来您正在循环计数器上寻找一些相当简单的数学:
def buildcount(listGroup):
for i in range (0, len(listGroup)):
x = (i % 10) * 5
d = (i // 10) * 10
print(f'i={i}, x={x}, d={d}')
return i
Output (for a 24-entry listGroup
): Output(对于 24 条目的
listGroup
):
i=0, x=0, d=0
i=1, x=5, d=0
i=2, x=10, d=0
i=3, x=15, d=0
i=4, x=20, d=0
i=5, x=25, d=0
i=6, x=30, d=0
i=7, x=35, d=0
i=8, x=40, d=0
i=9, x=45, d=0
i=10, x=0, d=10
i=11, x=5, d=10
i=12, x=10, d=10
i=13, x=15, d=10
i=14, x=20, d=10
i=15, x=25, d=10
i=16, x=30, d=10
i=17, x=35, d=10
i=18, x=40, d=10
i=19, x=45, d=10
i=20, x=0, d=20
i=21, x=5, d=20
i=22, x=10, d=20
i=23, x=15, d=20
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.