是否有更好的方法来查找某个字符的第一次出现:'x'、'y'、'z' 在 someStr 中?
def findFirstAppearance(someStr):
x = someStr.find('x');
y = someStr.find('y');
z = someStr.find('z');
if x == -1: x= len(someStr);
if y == -1: y= len(someStr);
if z == -1: z= len(someStr);
return min(x,y,z);
例如:对于 someStr = "axby"它应该返回 1。 对于 someStr = "aybx"它也应该返回 1。
谢谢!
最佳答案
也许:
>>> s = 'this string x contains y several letters z'
>>> next(i for i,c in enumerate(s) if c in 'xyz')
12
>>> s[12]
'x'
如果未找到,这将引发异常,这可以通过使用默认值来修复:
>>> next(i for i,c in enumerate(s) if c in 'Q')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
>>> next((i for i,c in enumerate(s) if c in 'Q'), -1)
-1
您还可以预先构建一个集合来测试以下位置的成员资格:
>>> special = set("vmp")
>>> next((i for i,c in enumerate(s) if c in special), -1)
27
如果有很多字母需要测试,可能会更快;这在很大程度上取决于所涉及的尺寸。如果重要的话很容易进行实验,但是(剧透警告)它可能并不重要。
关于python - 获取字符串中集合中任意字符的第一次出现 - python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15662516/