【发布时间】:2021-03-31 03:46:55
【问题描述】:
test = [1,2,3,4,5,6,7,8,9,10]
for t in test:
index = test.index(t)
print(str(t)+ ' Index: '+ str(test.index(t)))
print('\t\t'+str(test[test.index(t)]) + ' Index: ' + str(test.index(t)))
test[index] = test[index] + 1
print(test)
Outputs:
1 Index: 0
1 Index: 0
2 Index: 0
2 Index: 0
3 Index: 0
3 Index: 0
4 Index: 0
4 Index: 0
5 Index: 0
5 Index: 0
6 Index: 0
6 Index: 0
7 Index: 0
7 Index: 0
8 Index: 0
8 Index: 0
9 Index: 0
9 Index: 0
10 Index: 0
10 Index: 0
[11, 2, 3, 4, 5, 6, 7, 8, 9, 10]
由于某种原因,索引值 test.index(t) 每次遍历测试列表时都是 0? 但如果我要创建自己的索引跟踪变量:
test = [1,2,3,4,5,6,7,8,9,10]
index = 0
for t in test:
print(str(t)+ ' Index: '+ str(test.index(t)))
print('\t\t'+str(test[index]) + ' Index: ' + str(index))
test[index] = test[index] + 1
index += 1
print(test)
1 Index: 0
1 Index: 0
2 Index: 0
2 Index: 1
3 Index: 1
3 Index: 2
4 Index: 2
4 Index: 3
5 Index: 3
5 Index: 4
6 Index: 4
6 Index: 5
7 Index: 5
7 Index: 6
8 Index: 6
8 Index: 7
9 Index: 7
9 Index: 8
10 Index: 8
10 Index: 9
[2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
为什么 list.index(element) 不能正常工作。我完全不知道为什么这不起作用。意思是看起来合乎逻辑,我抓取元素的索引,然后将其更新 1。
【问题讨论】:
标签: python python-3.x list indexing