python - 在 Python 'for' 中计算项目编号?

标签 python

<分区>

Possible Duplicate:
for x in y, type iteration in python. Can I find out what iteration I'm currently on?
Iteration count in python?

有点难以解释,但是当我运行这样的东西时:

fruits = ['apple', 'orange', 'banana', 'strawberry', 'kiwi']

for fruit in fruits:
    print fruit.capitalize()

如预期的那样,它给了我这个:

Apple
Orange
Banana
Strawberry
Kiwi

我如何编辑该代码,以便它“计算”它执行 for 的次数,并打印出来?

1 Apple
2 Orange
3 Banana
4 Strawberry
5 Kiwi

最佳答案

for i,fruit in enumerate(fruits, 1):
    print i, fruit.capitalize()

将做你想做的并打印:

1 Apple
2 Orange
3 Banana
4 Strawberry
5 Kiwi

默认 enumerate()如果未指定,将开始生成 0 索引,但您可以指定起始值,如图所示。

关于python - 在 Python 'for' 中计算项目编号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10866411/

相关文章:

python 无法访问 suds 方法

python - Cython:导致段错误的堆栈分配对象的赋值运算符

Python套接字不传送数据包

python - 哪种方式将字典附加到列表更有效

python - 实时远程获取Python的输出

python - 为图例中的点设置固定大小

python - 在 Python 中使用中文

python - 在 Python 中运行来自 maya 的 cmd.exe 命令列表

python - 模块化 pow() 中的负幂

python - 将空格分隔的树转换为 python 中有用的字典