程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长

+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

python检索字符串/列表/元组中元素的位置 find()/index()

发布于2019-08-07 11:58     阅读(742)     评论(0)     点赞(1)     收藏(5)


查找元素位置,对于字符串,
str.find(str, beg=0, end=len(string))
str.index(str, beg=0, end=len(string))

s = 'hello, world!'

s.find('l')
#2
s.index('l')
#2
s.find('l', len(s) - 5)
#10

s.find('world')
s.index('world')
#7

s.find('Hello')
#-1
s.index('Hello')
#ValueError: substring not found
s.index('Hello') if 'Hello' in s else -1
#-1
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

对于列表(元组同理):
list.index(obj)

lst = [1,2,'ad','c']

lst.index(1)
#0
lst.index('c')
#3
lst.index('hehe')
#ValueError: 'hehe' is not in list
lst.index('hehe') if 'hehe' in lst else -1
#-1

'''
同str,也可切片
'''
lst = ['b','b','b',1, 2,'b']
lst.index('b')
#0
lst.index('b', 2, 4)
#2
lst.index('b',-1) #注意这里和字符串中的使用区别,begin可以不为0
#5
lst.index('b',-2)
#5
lst.index('b',-3)
#5
lst.index('b',-4)
#2
lst.index('b',-5)
#1

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30

元组举例:

from itertools import permutations
sequence = [_ for _ in permutations([1,2,3,4,5])] 
#len = 120
len([_ for _ in sequence if _.index(1) == 0])
#24

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

总结:

1、find()和index()两者区别在于,遇到没有的元素时:
find会返回-1
index会报错

2、index()在str中,begin=0, end=len(string)
而index()在list中,begin可以为负



所属网站分类: 技术文章 > 博客

作者:小白鼠

链接:https://www.pythonheidong.com/blog/article/10547/46d451ff16da3d4e86c4/

来源:python黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

1 0
收藏该文
已收藏

评论内容:(最多支持255个字符)