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