如何在python中使用int迭代字符串列表? [英] How can I iterate over a list of strings with ints in python?

查看:816
本文介绍了如何在python中使用int迭代字符串列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚开始使用python和编程进行编程,遇到了以下问题:

I'm new to programming with python and programming in general and got stuck wit the following problem:

b=["hi","hello","howdy"]
for i in b:
    print i

#This code outputs:
hi
hello
howdy

我如何才能使迭代变量成为一个int,因此它可以工作以下方式?

How can I make it so the iterating variable is an int so it works the following way?

b=["hi","hello","howdy"]
for i in b:
    print i

#I want it to output:
0
1
2


推荐答案

Pythonic的方式是 enumerate()

The Pythonic way would be with enumerate():

for index, item in enumerate(b):
    print index, item

还有范围(len(b)),但你几乎总是会检索<循环体中code> item ,所以 enumerate()是大部分时间更好的选择:

There's also range(len(b)), but you almost always will retrieve item in the loop body, so enumerate() is the better choice most of the time:

for index in range(len(b)):
    print index, b[index]

这篇关于如何在python中使用int迭代字符串列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆