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

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

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

您可以将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


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5508480.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-12-13
下一篇2022-12-13

发表评论

登录后才能评论

评论列表(0条)

    保存