如何在python中自动递增

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40297409/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 23:22:19  来源:igfitidea点击:

How to auto-increment in python

python

提问by Yethrosh

I am new to python. I want to print all available functions in os module as:

我是python的新手。我想将 os 模块中的所有可用函数打印为:

1 functionName

2 functionName

3 functionName

and so on.

等等。

Currently I am trying to get this kind of output with following code:

目前我正在尝试使用以下代码获得这种输出:

import os

cur = dir(os)
for i in cur:
    count = 1
    count += 1
    print(count,i)

But it prints as below:

但它打印如下:

2 functionName

2 functionName

2 functionName

till end.

直到结束。

Please help me generate auto increment list of numbers, Thanks.

请帮我生成数字的自动递增列表,谢谢。

回答by Pragun

Its because you've re-defined the countvariable or reset it to 1 for each loop again. I'm not into python but your code doesn't make sense since everytime the count variable is first set to 1 and then incremented. I'd simply suggest the following.

这是因为您重新定义了count变量或再次为每个循环将其重置为 1。我不喜欢 python 但你的代码没有意义,因为每次 count 变量首先设置为 1 然后递增。我只是建议以下。

import os

cur = dir(os)
count = 1
for i in cur:
    count += 1
    print(count,i)

回答by Paul Rooney

The pythonic way to do this is enumerate. If we pass the keyword argument start=1, the count will begin at 1 instead of the default 0.

执行此操作的 Pythonic 方法是enumerate。如果我们传递关键字参数start=1,计数将从 1 开始,而不是默认的 0。

import os

cur = dir(os)
for i, f in enumerate(cur, start=1):
    print("%d: %s" % (i, f))