广告
返回顶部
首页 > 资讯 > 后端开发 > Python >python打印列表中指定元素的所有下标
  • 943
分享到

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

下标元素列表中 2023-01-31 07:01:09 943人浏览 安东尼

Python 官方文档:入门教程 => 点击学习

摘要

1》法一: song@ubuntu:~$ vi find2.py song@ubuntu:~$ more find2.py l=[1,2,3,4,7

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

(完)

--结束END--

本文标题: python打印列表中指定元素的所有下标

本文链接: https://www.lsjlt.com/news/192141.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作