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


