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

标签 python

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

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

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

最佳答案

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

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

关于python - 在嵌套的for循环中获取迭代计数器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13181700/

相关文章:

python - 动态压缩字符串并附加到文件

python - 如何将类似网格的 matplotlib 图转换为平滑渐变的曲面?

python - 尝试在列表 python 的每个值之间添加逗号

python - 如何修复将 $ 解释为 $text $ 中的定界符的数据框?

python - sklearn 绘制带有标签的混淆矩阵

python - itertools.dropwhile 有困难

python - 拆分和追加

python - 在 Python 中使用子进程

python - 检查字符串中是否仅存在指定的 Django 模板变量

python - 使用未实例化的类作为 namespace 来组织对象?