【问题标题】:Finding the index of a list in a loop在循环中查找列表的索引
【发布时间】:2010-08-23 17:14:20
【问题描述】:

我有一个简单的问题。如果我在python中有一个for循环如下:

for name in nameList:

我如何知道元素名称的索引是什么?我知道我可以这样做:

i = 0
for name in nameList:
    i= i + 1
    if name == "something":
        nameList[i] = "something else"

我只是觉得应该有一种更易读的方式来做到这一点......

【问题讨论】:

    标签: python loops


    【解决方案1】:

    使用内置函数enumerate

    for index, name in enumerate(nameList):
        ...
    

    【讨论】:

    • 谢谢,这正是我想要的
    猜你喜欢
    • 1970-01-01
    • 2022-08-03
    • 1970-01-01
    • 1970-01-01
    • 2018-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-11
    相关资源
    最近更新 更多