increment counter in for loop python [closed]

孤街浪徒 提交于 2019-12-25 17:06:10

问题


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] + ",&nbsp;""&nbsp;High/Low:" + DATA[k][10:] + ",&nbsp;&nbsp;" + STATUS[k] + "&nbsp;&nbsp;" + "<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] + ",&nbsp;""&nbsp;High/Low:" + DATA[i][10:] + ",&nbsp;&nbsp;" + STATUS[i] + "&nbsp;&nbsp;" + "<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] + ",&nbsp;""&nbsp;High/Low:" + DATA[0][10:] + ",&nbsp;&nbsp;" + STATUS[0] + "&nbsp;&nbsp;" + "<br/><br/>"

or

return f"{DATA[0][:9]},&nbsp;""&nbsp;High/Low:{DATA[0][10:]},&nbsp;&nbsp;{STATUS[0]}&nbsp;&nbsp;<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] + ",&nbsp;""&nbsp;High/Low:" + DATA[i][10:] + ",&nbsp;&nbsp;" + STATUS[i] + "&nbsp;&nbsp;" + "<br/><br/>"

print(*get_days())


来源:https://stackoverflow.com/questions/59377649/increment-counter-in-for-loop-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!