查找元素位置,对于字符串,
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
对于列表(元组同理):
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
元组举例:
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、find()和index()两者区别在于,遇到没有的元素时:
find会返回-1
index会报错
2、index()在str中,begin=0, end=len(string)
而index()在list中,begin可以为负