【问题标题】:Enumerate stops counting after returning a function in Python在 Python 中返回函数后枚举停止计数
【发布时间】:2020-06-27 12:30:43
【问题描述】:

我的问题是我想在我的工作人员中调用return logout(),但这确实会破坏枚举并将idx 计数器设置为0,因此它不会打印item。怎样才能在没有这个问题的情况下返回注销?

代码:

import time

def logout():
    print("logout")

N = 4
def worker():
    for idx, Item in enumerate(range(1, 12)):
        if idx % N == 0:
            print("Done Session") 
            time.sleep(1)
            return logout()
        print(Item)    

worker()
worker()
worker()

输出:

Done Session
logout
Done Session
logout
Done Session
logout

预期输出:

Done Session
logout
1
2
3
4
Done Session
logout
5
6
7
8
Done Session
logout
...

【问题讨论】:

  • @PETERSTACEY 否,因为打印调用与 if 语句有关。在 if 之前调用它会在 1x 之后停止计数。

标签: python python-3.x function loops enumeration


【解决方案1】:

您可以将必要的东西存储在一个列表中,然后一次将它们全部返回(注意:我注释了一些输出不需要的代码行)

N = 4
def worker():
    log = [] # Not needed
    for idx, Item in enumerate(range(1, 12)):
        if idx % N == 0:
            print("Done Session") 
            time.sleep(1)
            log.append(logout()) # logout()
        print(Item)
    return log # Not needed

结果:

Done Session
logout
1
2
3
4
Done Session
logout
5
6
7
8
Done Session
logout
9
10
11
Done Session
logout
1
2
3
4
Done Session
logout
5
6
7
8
Done Session
logout
9
10
11
Done Session
logout
1
2
3
4
Done Session
logout
5
6
7
8
Done Session
logout
9
10
11

【讨论】:

    【解决方案2】:

    这将起作用:

    N = 4
    def worker():
        for idx, Item in enumerate(range(1, 12)):
            if idx % N == 0:
                print("Done Session") 
                time.sleep(1)
                logout()
            print(Item) 
    

    【讨论】:

      猜你喜欢
      • 2012-08-20
      • 1970-01-01
      • 1970-01-01
      • 2019-03-22
      • 1970-01-01
      • 2023-04-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多