Skip to main content
 首页 » 编程设计

python之在嵌套的for循环中获取迭代计数器

2025年05月04日15txw1958

我想要一个计数器来计算我总共完成了多少次迭代。 我这样做:

counter = 0; 
for i, item in enumerate(items): 
    for j, anotheritem in enumerate(anotheritems): 
        counter += 1; 

但我不禁要问有没有更pythonic的方式?

请您参考如下方法:

它简单易读,几乎是 Pythonic 的(除了分号。)

我唯一的建议是,如果您开始将更多代码放入这些循环中,请为 i 和 j 提供更具描述性的名称。