簡體   English   中英

如何僅在循環結束時將數字加一?

[英]How can I increase number by one only when the loop is over?

我試圖僅在循環結束時將數字加一,然后我想用加一的新數字再次激活此循環。

for l in range(len(listc)):
  n+=1
  for item in new['stuff']:
   c+=1
   try:
    st = item[list1[c]]
    if org[c].startswith(listc[n]):
        byte += len(item["In"]+"1234")
        print(len(item["In"]+"1234"))
        if listc[c] == sorted_listc[1]:
            listc[c] = org[c][0:len(common)+1]
        print(hex(byte))
    else:
        pass


   except:
       continue

我希望每次 new['stuff'] 循環結束時,n 都會增加 1。 不知何故它不起作用,有什么幫助嗎?

正如您提供的代碼一樣,您在內循環(通過new['stuff'] )開始之前增加了n上的值。

嘗試將增加傳遞到內部循環的末尾。

n = 0
for l in range(len(listc)):
    for item in new['stuff']:
        ### do stuff
    n += 1

您還可以嘗試使用Statements 和 else Clauses on Loops

循環語句可能有一個else子句; 當循環因可迭代對象耗盡終止時執行。

例如:

n = 0
for i in range(1, 5):
    for j in range(1, 3):
        print(i*j)
    else:
        n += 1

將導致:

1
2
2
4
3
6
4
8
>>> print(n)
4

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM