问题
I am familiar with python codes and now trying to learn writing short and effective codes. here i am trying to increment inside a for loop but I am not sure if iam doing right.
k = 0
if limit == "4 days":
day = DATA[k][:9] + ", "" High/Low:" + DATA[k][10:] + ", " + STATUS[k] + " " + "<br/><br/>"
for i in range(k):
if k == 3:
break
k += 1
return day
it should print day when k is equal to 0, 1, 2 and 3 -> so, 4 lines the output should be!
回答1:
k
is 0 so you won't have anything to loop over, and even if it did, your for loop doesn't do anything, instead since you've specified a limit, just set that limit to what you're range is supposed to use
for i in range(k):
day = DATA[i][:9] + ", "" High/Low:" + DATA[i][10:] + ", " + STATUS[i] + " " + "<br/><br/>"
Having said that, you only return the first iteration of the for loop too, so just skip the loop
return DATA[0][:9] + ", "" High/Low:" + DATA[0][10:] + ", " + STATUS[0] + " " + "<br/><br/>"
or
return f"{DATA[0][:9]}, "" High/Low:{DATA[0][10:]}, {STATUS[0]} <br/><br/>"
To get your desired output, you need to not use return inside the for loop, add your items to a collection of some sort and then print those as required
def get_days():
for i in range(k):
yield DATA[i][:9] + ", "" High/Low:" + DATA[i][10:] + ", " + STATUS[i] + " " + "<br/><br/>"
print(*get_days())
来源:https://stackoverflow.com/questions/59377649/increment-counter-in-for-loop-python