【问题标题】:How can I iterate over a list of strings with ints in python?如何在 python 中迭代带有整数的字符串列表?
【发布时间】:2013-10-16 01:55:06
【问题描述】:

我是 python 编程和一般编程的新手,遇到以下问题:

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

#This code outputs:
hi
hello
howdy

我怎样才能使它的迭代变量是一个 int 所以它的工作方式如下?

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

#I want it to output:
0
1
2

【问题讨论】:

    标签: python variables loops int


    【解决方案1】:

    Pythonic 方式是enumerate():

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

    还有range(len(b)),但你几乎总是会在循环体中检索item,所以enumerate()在大多数情况下是更好的选择:

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

    【讨论】:

    • 非常感谢,我不敢相信我花了多长时间才找到这个答案。
    【解决方案2】:
    b=["hi","hello","howdy"]
    for count,i in enumerate(b):
        print count
    

    【讨论】:

      【解决方案3】:

      你总是可以这样做:

      b=["hi","hello","howdy"]
      for i in range(len(b)):
          print i
      

      【讨论】:

        猜你喜欢
        • 2019-11-29
        • 1970-01-01
        • 2018-12-03
        • 1970-01-01
        • 1970-01-01
        • 2019-07-15
        • 1970-01-01
        • 1970-01-01
        • 2019-03-01
        相关资源
        最近更新 更多