my code currently
so basically this is my code now and i only want one 'end' to be printed when it detects a value 0 in my excel sheet. The main output i want is when the value is '1', like in this image (main output) but without so many 'end's.
#Duration loop
for i in range(len(dfDur01Mar22)):
#only display bus 'SG3079S'
if dfDur01Mar22.iloc[i,1] == 'SG3079S':
#print 'end' when first '0' appears
if dfDur01Mar22.iloc[i,2] == 0:
print('end')
#if charging type is 1
elif dfDur01Mar22.iloc[i,2] == 1: print(dfDur01Mar22.iloc[i,0],dfDur01Mar22.iloc[i,1],dfDur01Mar22.iloc[i,2])
main output
CodePudding user response:
I believe @TimRoberts in the comments gave the correct answer, I will just expand upon it by showing you how to use it.
I slightly modified your code as I did not have your file, but the concept is all that's important. You use a simple bool variable as a sentinel and check if it is set, if it isn't then run the rest of the check for the end value. This is probably the best way to solve this type of problem from the information you have provided. Code:
import random
dfDur01Mar22 = []
for i in range(0,20):
chargingType = random.choice([0, 1, 1])
dfDur01Mar22.append(['', 'SG3079S', chargingType])
foundEnd = False
#Duration loop
for i in range(len(dfDur01Mar22)):
#only display bus 'SG3079S'
if dfDur01Mar22[i][1] == 'SG3079S':
#print 'end' when first '0' appears
if not foundEnd and dfDur01Mar22[i][2] == 0:
print('end')
foundEnd = True
#if charging type is 1
elif dfDur01Mar22[i][2] == 1:
print(dfDur01Mar22[i][0],dfDur01Mar22[i][1],dfDur01Mar22[i][2])
Example of output:
With check : Without check
SG3079S 1 SG3079S 1
SG3079S 1 SG3079S 1
SG3079S 1 SG3079S 1
SG3079S 1 end
end end
SG3079S 1 SG3079S 1
SG3079S 1 end
SG3079S 1 SG3079S 1
SG3079S 1 end
SG3079S 1 SG3079S 1
SG3079S 1 SG3079S 1
SG3079S 1 end
end
SG3079S 1
SG3079S 1
SG3079S 1
SG3079S 1
SG3079S 1
SG3079S 1
SG3079S 1