首页 > 编程语言 > 详细

Python求列表中某个元素的下标

时间:2017-10-25 18:57:42      阅读:212      评论:0      收藏:0      [点我收藏+]

一、求列表中某个元素的下标

def findindex(org, x, pos=-1):
    counts = org.count(x)   #先求出org中包含x的个数
    if counts == 0:    #个数为0,说明不存在x
        print(org, 中没有, x)
    elif counts == 1:   #个数为1,说明结果唯一,直接返回index(x)
        print(org.index(x))
    else:
        ‘‘‘
        个数大于1时,从下标为0的位置开始查找
        找到一个后,先打印下标位置,再从该位置的下一个位置开始继续查找
        ‘‘‘ 
        for i in range(counts):    
            pos = org.index(x, pos + 1)
            print(pos,end= )
        print()

org = [1, 2, 2, 33, 2, 4, 5, 2]
findindex(org, 3)
findindex(org, 2)
findindex(org, 1)

 

查看结果:

[1, 2, 2, 33, 2, 4, 5, 2] 中没有 3
1 2 4 7 
0

 

Python求列表中某个元素的下标

原文:http://www.cnblogs.com/jessicaxu/p/7730233.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!