I am trying to open a csv file in python and read the rows into a list.
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.
d I have working but can't quite figure out 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.
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
CodePudding user response:
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
):
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
CodePudding user response:
It looks like you want x
to reset after 50 and then increment d after reaching multiples of ten. This uses mod (%
) for the first, and just integer division for the second.
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