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

2024-06-10 05:04:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我想找到字符串中任何“特殊”字符第一次出现的索引,如下所示:

>>> "Hello world!".index([' ', '!'])
5

…但那不是有效的Python语法。当然,我可以编写一个模拟此行为的函数:

def first_index(s, characters):
    i = []
    for c in characters:
        try:
            i.append(s.index(c))
        except ValueError:
            pass
    if not i:
        raise ValueError
    return min(i)

我也可以使用正则表达式,但这两种解决方案似乎都有点过头了。在Python中有什么“理智”的方法可以做到这一点吗?


Tags: 函数字符串inhelloforworldindexdef
3条回答

使用gen exp和^{}方法。

>>> a = [' ', '!']
>>> s = "Hello World!"
>>> min(s.find(i) for i in a)
5

若要删除出现的-1s,可以在列表组件中使用筛选器

>>> a = [' ', '!','$']
>>> s = "Hello World!"
>>> min(s.find(i) for i in a if i in s)
5

或者你可以用None

>>> min(s.find(i) if i in s else None for i in a)
5

添加timeit结果

$ python -m timeit "a = [' ', '\!'];s = 'Hello World\!';min(s.find(i) for i in a if i in s)"
1000000 loops, best of 3: 0.902 usec per loop
$ python -m timeit "a = [' ', '\!'];s = 'Hello World\!';next((i for i, ch  in enumerate(s) if ch in a),None)"
1000000 loops, best of 3: 1.25 usec per loop
$ python -m timeit "a = [' ', '\!'];s = 'Hello World\!';min(map(lambda x: (s.index(x) if (x in s) else len(s)), a))"
1000000 loops, best of 3: 1.12 usec per loop

在你的例子中,Padraic的漂亮解决方案有点慢。然而,在大型测试用例中,它绝对是赢家。(有点奇怪的是,alfasin的“没有优化”在这里也更快)

添加了实现细节

>>> def take1(s,a):
...     min(s.find(i) for i in a if i in s)
... 
>>> import dis
>>> dis.dis(take1)
  2           0 LOAD_GLOBAL              0 (min)
              3 LOAD_CLOSURE             0 (s)
              6 BUILD_TUPLE              1
              9 LOAD_CONST               1 (<code object <genexpr> at 0x7fa622e961b0, file "<stdin>", line 2>)
             12 MAKE_CLOSURE             0
             15 LOAD_FAST                1 (a)
             18 GET_ITER            
             19 CALL_FUNCTION            1
             22 CALL_FUNCTION            1
             25 POP_TOP             
             26 LOAD_CONST               0 (None)
             29 RETURN_VALUE        
>>> def take2(s,a):
...     next((i for i, ch  in enumerate(s) if ch in a),None)
... 
>>> dis.dis(take2)
  2           0 LOAD_GLOBAL              0 (next)
              3 LOAD_CLOSURE             0 (a)
              6 BUILD_TUPLE              1
              9 LOAD_CONST               1 (<code object <genexpr> at 0x7fa622e96e30, file "<stdin>", line 2>)
             12 MAKE_CLOSURE             0
             15 LOAD_GLOBAL              1 (enumerate)
             18 LOAD_FAST                0 (s)
             21 CALL_FUNCTION            1
             24 GET_ITER            
             25 CALL_FUNCTION            1
             28 LOAD_CONST               0 (None)
             31 CALL_FUNCTION            2
             34 POP_TOP             
             35 LOAD_CONST               0 (None)
             38 RETURN_VALUE        
>>> def take3(s,a):
...     min(map(lambda x: (s.index(x) if (x in s) else len(s)), a))
... 
>>> dis.dis(take3)
  2           0 LOAD_GLOBAL              0 (min)
              3 LOAD_GLOBAL              1 (map)
              6 LOAD_CLOSURE             0 (s)
              9 BUILD_TUPLE              1
             12 LOAD_CONST               1 (<code object <lambda> at 0x7fa622e44eb0, file "<stdin>", line 2>)
             15 MAKE_CLOSURE             0
             18 LOAD_FAST                1 (a)
             21 CALL_FUNCTION            2
             24 CALL_FUNCTION            1
             27 POP_TOP             
             28 LOAD_CONST               0 (None)
             31 RETURN_VALUE        

在Padraic的例子中可以清楚地看到,加载全局函数nextenumerate是与最后的None一起消磨时间的函数。在alfasin的溶液中,主要的减慢是lambda函数。

我更喜欢re模块,因为它已经内置并测试过了。它也正是为这种事情而优化的。

>>> import re
>>> re.search(r'[ !]', 'Hello World!').start()
5

您可能希望检查是否找到匹配项,或者在没有找到匹配项时捕获异常。

不使用re是有原因的,但是我想看到一个很好的注释来证明rational的合理性。认为您可以“做得更好”通常是不必要的,这会使其他人更难阅读代码,并且不易维护。

可以将enumeratenextgenerator expression一起使用,获取第一个匹配项,如果在s中没有出现字符,则返回None:

s = "Hello world!"

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

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

如果要使用函数并引发值错误:

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]: %%timeit
st = {"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]: %%timeit
specials = ['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]: %%timeit
st = {"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 loop

In [45]: %%timeit
specials = ["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]: %%timeit
specials = ['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 loop

In [48]: %%timeit
st = {"H","y","!"}
next((i for i, ch in enumerate(s) if ch in st), None)
   ....: 
1000000 loops, best of 3: 903 ns per loop

相关问题 更多 >