开发者

Finding the index of a list in a loop

开发者 https://www.devze.com 2023-01-12 14:06 出处:网络
I have a simple question. If I have a for loop in python as follows: for name in nameList: How do I know what the i开发者_运维技巧ndex is for the element name? I know I can some something like:

I have a simple question. If I have a for loop in python as follows:

for name in nameList:

How do I know what the i开发者_运维技巧ndex is for the element name? I know I can some something like:

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

I just feel there should be a more readable way of doing this...


Use the built in function enumerate.

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

精彩评论

暂无评论...
验证码 换一张
取 消