栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何查找字符串中任何字符集的第一个索引

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何查找字符串中任何字符集的第一个索引

您可以将enumerate和next与生成器表达式一起使用,获取第一个匹配项,或者如果s中没有字符,则返回None:

s = "Hello world!"st = {"!"," "}ind = next((i for i, ch  in enumerate(s) if ch in st),None)print(ind)

如果没有匹配项,则可以将您想要的下一个值作为默认返回值传递。

如果要使用函数并引发ValueError:

def first_index(s, characters):    st = set(characters)    ind = next((i for i, ch in enumerate(s) if ch in st), None)    if ind is not None:        return ind    raise ValueError

对于较小的输入,使用集合不会有什么区别,但是对于较大的字符串,则效率更高。

一些时间:

在字符串中,字符集的最后一个字符:

In [40]: s = "Hello world!" * 100    In [41]: string = s    In [42]: %%timeitst = {"x","y","!"}next((i for i, ch in enumerate(s) if ch in st), None)   ....: 1000000 loops, best of 3: 1.71 µs per loop    In [43]: %%timeitspecials = ['x', 'y', '!']min(map(lambda x: (string.index(x) if (x in string) else len(string)), specials))   ....: 100000 loops, best of 3: 2.64 µs per loop

不在字符串中,较大的字符集:

In [44]: %%timeitst = {"u","v","w","x","y","z"}next((i for i, ch in enumerate(s) if ch in st), None)   ....: 1000000 loops, best of 3: 1.49 µs per loopIn [45]: %%timeitspecials = ["u","v","w","x","y","z"]min(map(lambda x: (string.index(x) if (x in string) else len(string)), specials))   ....: 100000 loops, best of 3: 5.48 µs per loop

在字符串中,字符集的第一个字符:

In [47]: %%timeitspecials = ['H', 'y', '!']min(map(lambda x: (string.index(x) if (x in string) else len(string)), specials))   ....: 100000 loops, best of 3: 2.02 µs per loopIn [48]: %%timeitst = {"H","y","!"}next((i for i, ch in enumerate(s) if ch in st), None)   ....: 1000000 loops, best of 3: 903 ns per loop


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/517208.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号