失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > python中列表下标 python打印列表中指定元素的所有下标

python中列表下标 python打印列表中指定元素的所有下标

时间:2021-08-15 22:15:34

相关推荐

python中列表下标 python打印列表中指定元素的所有下标

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

(完)

如果觉得《python中列表下标 python打印列表中指定元素的所有下标》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。