遍历一个列表[1,2,3,4,1,5,1],请判断列表里面是否有1,有的话打印 下标位置和find it字符串
- 如果list中有重复值,并且直接从list中遍历取值,会有个坑:因为列表是从左至右一次遍历查找的,相同元素的下标都为第一个元素的下标,导致计算不准确,如下:
seq = [1,2,3,4,1,5,1]
for i in seq:
# print seq.index(i)
if i ==1:
print seq.index(i),'find it'
else:
print seq.index(i)
#返回结果为:
0 find it
1
2
3
0 find it
5
0 find it
- 正确的算法应该是直接根据下标取值,找到目标元素后直接打印下标即可,如下:
seq = [1,2,3,4,1,5,1]
for i in range(len(seq)):
# print seq.index(i)
if seq[i] ==1:
print i,'find it'
else:
print i
#返回结果为:
0 find it
1
2
3
4 find it
5
6 find it