python打印列表中指定元素的所有下标(5种方法)

本文介绍五种不同的Python方法来找出列表中特定元素的所有出现位置,包括使用循环、索引更新等技术。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

(完)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值