我必须在 python 中访问列表成员的索引.我想打印索引的位置.但是在我的代码中,如果条件,我无法签入它


s='hello'
new=list(s)
for i in new:
if new[i]%2==0:
print(i)
else:
print(i)

在这里new[i]不返回索引,代码给出错误。如何访问列表索引?

使用enumerate访问索引:

s='hello'
new=list(s)
for index, value in enumerate(new):
if value == 'e':  # This looks for 'e' in the list and return index 1
print(index)

输出:

1 

最好的方法是使用内置函数 numerate((。文档链接如下:

枚举链接

我将用于此问题的代码如下:

s='hello'
new=list(s)
for index, value in enumerate(new):
print(index) # or print (index,value) to see both the index and values in

最新更新