Python列表元素索引疑问:为何前三次循环sq值始终为0?
问题分析:为什么前三次迭代中sq始终返回0?
我明白你这两天的困惑了——前三次循环里sq总是返回0,完全不符合预期的0、1、2对吧?咱们来揪出问题的根源:
核心问题:list.index()的行为不是你想的那样
你代码里获取sq的关键行是:
sq = sequence2.index(sequence2[-1])
list.index(x)方法的作用是返回列表中第一个匹配x的元素的索引。前三次循环中,你向sequence2添加的都是1:
- 第一次循环后
sequence2 = [1],找1的索引是0,没问题; - 第二次循环后
sequence2 = [1,1],找1的索引还是第一个1的位置——0; - 第三次循环后
sequence2 = [1,1,1],同样,index(1)返回的还是第一个1的索引0。
这就是为什么前三次sq都返回0的原因!
解决方案:直接获取最后一个元素的索引
既然你需要的是最后一个添加元素的索引,根本不需要用index()方法,直接用列表长度减一就可以了:
sq = len(sequence2) - 1
因为列表的索引从0开始,最后一个元素的位置永远等于列表当前长度减一,不管元素是否重复,这个方法都能精准拿到最后一个元素的索引。
修改后的代码及运行输出
把代码里的sq = sequence2.index(sequence2[-1])替换成sq = len(sequence2) - 1,运行结果就会符合你的预期:
修改后的完整代码:
sequence = [1, 1, 1, 2, 3] sequence2 = [] k = 0 if len(sequence) == 2 or len(sequence) == 1: print('Great!') else: for element in range(0, (len(sequence))): sequence2.append(sequence[element]) sq = len(sequence2) - 1 # 这里是修改的核心行 print(sequence2, sq) if sequence2 == sorted(sequence2): print('This is good thus far:', sequence2) else: print(sequence2[sq-1], sequence2[sq]) print(sequence2.index(sequence2[-1])) if sequence2[sq-1] >= sequence2[sq]: sequence2.pop(sequence2.index(sequence2[sq - 1])) print('We poppoed an element') print(sequence2) k = k+1 if k >= 2: print(sequence2) print('This doesnt work') else: print('Works properly!')
对应的输出:
[1] 0 This is good thus far: [1] Works properly! [1, 1] 1 This is good thus far: [1, 1] This doesnt work [1, 1, 1] 2 This is good thus far: [1, 1, 1] This doesnt work [1, 1, 1, 2] 3 This is good thus far: [1, 1, 1, 2] This doesnt work [1, 1, 1, 2, 3] 4 This is good thus far: [1, 1, 1, 2, 3] This doesnt work
你看,前三次的sq现在依次是0、1、2,完全符合你的预期了!
额外提示
如果以后需要找列表中最后一个匹配元素的索引,可以用反向遍历的方式,比如:
# 找sequence2中最后一个1的索引 last_index = len(sequence2) - 1 - sequence2[::-1].index(1)
不过在你的场景里,因为你是刚添加完元素,直接用len(sequence2)-1是最简洁高效的方式。
内容的提问来源于stack exchange,提问作者insp
相关产品推荐
相关产品推荐

