发布于2019-08-07 11:58 阅读(800) 评论(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
对于列表(元组同理):
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可以为负
作者:小白鼠
链接:https://www.pythonheidong.com/blog/article/10547/46d451ff16da3d4e86c4/
来源:python黑洞网
任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任
昵称:
评论内容:(最多支持255个字符)
---无人问津也好,技不如人也罢,你都要试着安静下来,去做自己该做的事,而不是让内心的烦躁、焦虑,坏掉你本来就不多的热情和定力
Copyright © 2018-2021 python黑洞网 All Rights Reserved 版权所有,并保留所有权利。 京ICP备18063182号-1
投诉与举报,广告合作请联系vgs_info@163.com或QQ3083709327
免责声明:网站文章均由用户上传,仅供读者学习交流使用,禁止用做商业用途。若文章涉及色情,反动,侵权等违法信息,请向我们举报,一经核实我们会立即删除!