博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python打印列表中指定元素的所有下标(5种方法)
阅读量:4170 次
发布时间:2019-05-26

本文共 1226 字,大约阅读时间需要 4 分钟。

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

(完)

转载地址:http://mcyai.baihongyu.com/

你可能感兴趣的文章
Java核心技术 卷I 基础知识 学习笔记(8)
查看>>
Java核心技术 卷I 基础知识 学习笔记(9)
查看>>
Intellij IDEA 创建资源文件夹 source folder
查看>>
Java核心技术卷2 高级特性 学习笔记(1)
查看>>
Java核心技术卷2 高级特性 学习笔记(4)
查看>>
最大乘积
查看>>
最长公共子串
查看>>
codeforces831c 思维
查看>>
CodeForces - 785C Anton and Fairy Tale
查看>>
CodeForces - 831D Office Keys
查看>>
hdu 1258 确定比赛名次
查看>>
hdu 3342 拓扑,是否存在环
查看>>
poj 1860 拓扑。。
查看>>
poj 2553 The Bottom of a Graph 未完
查看>>
inux下如何统计一个目录下的文件个数以及代码总行数(转)
查看>>
Linux下 虚拟机Bochs的使用
查看>>
glib-读取配置文件
查看>>
SonarQube 静态代码检查的安装
查看>>
嵌入式Linux驱动开发的知识图谱
查看>>
Algorithm 4th environment setup
查看>>