1》法一:
song@ubuntu:~$ vi find2.py
song@ubuntu:~$ more find2.py
l=[1,2,3,4,7,2,5,6,2,8,9,0]
first=0
for i in range(l.count(2)):
new_l=l[first:]
index=first+new_l.index(2)
print 'find the index of 2:',index
first=index+1
song@ubuntu:~$ python find2.py
find the index of 2: 1
find the index of 2: 5
find the index of 2: 8
song@ubuntu:~$
2》法二:
song@ubuntu:~$ vi find_2.py
song@ubuntu:~$ more find_2.py
l=[2,2,3,4,5,1,2,3,1,2,3,4,5]
first=True
for i in range(l.count(2)):
if first==True:
pos=l.index(2)
first=False
else:
pos=l.index(2,pos+1)
print pos
song@ubuntu:~$ python find_2.py
0
1
6
9
song@ubuntu:~$
3》法三:
song@ubuntu:~$ vi find_2_1.py
song@ubuntu:~$ more find_2_1.py
l=[2,2,3,4,5,1,2,3,1,2,3,4,5]
for i in range(len(l)):
if l[i]==2:
print i
song@ubuntu:~$ python find_2_1.py
0
1
6
9
song@ubuntu:~$
4》法四:
song@ubuntu:~$ vi find_2.py
song@ubuntu:~$ more find_2.py
l=[2,2,3,4,5,1,2,3,1,2,3,4,5]
for i in range(l.count(2)):
if i==0:
pos=l.index(2)
else:
pos=l.index(2,pos+1)
print pos
song@ubuntu:~$ python find_2.py
0
1
6
9
5》法五:
song@ubuntu:~$ vi find_2.py
song@ubuntu:~$ more find_2.py
l=[2,2,3,4,5,1,2,3,1,2,3,4,5]
pos=-1
for i in range(l.count(2)):
pos=l.index(2,pos+1)
print pos
song@ubuntu:~$ python find_2.py
0
1
6
9
(完)