Skip to main content
 首页 » 编程设计

python之获取 python 字符串中字符集的位置

2025年05月04日21kevingrace

获取 python 字符串中字符集的位置

字符集:

    string="ABCDEFGHIJKLMNOPQRSTUVWXYZ" 
    charPositionToFind=A,D,V,Y 

预期输出

    postions=[0,3,21,24] 

我是这样做的

 def find_all(string,char): 
     return [i - 1 for i in range(len(string)) if string.startswith(char, i - 1)] 
 
 string="ABCDEYYFGHIAAJKVLMNOPDCQRSTAAVVVUVWXYZ" 
 charPositionToFind=['A','D','V','Y'] 
 position=[] 
 
 for char in charPositionToFind: 
    s = find_all(string,char) 
    position.extend(s) 
 print sorted(position) 
 
  output: 
       [0, 3, 5, 6, 11, 12, 15, 21, 27, 28, 29, 30, 31, 33, 36] 

但我想要最好的方法来做到这一点

请您参考如下方法:

string.index 会很好用,但它有两个问题。 1)它只找到字符的第一次出现,并且 2) 如果找不到该字符,它会引发错误,需要在使用 index() 之前检查是否存在。

简单地看问题,这是解决问题的两种简单方法:

方法一:

for character in the string: 
    for target in charPositionToFind: 
        test if character == target 

方法二:

for target in charPositionToFind: 
    for character in the string: 
        test if character == target 

在运行时方面,这两种方法具有相同的最坏情况 O(N x M),其中 N 是字符串的大小,M 是 charPositionToFind 的大小。但是,使用方法 1 允许您通过使用集合来删除内部循环。它还避免了必须在最后进行排序,因为您正在按顺序遍历字符串的字符。因此,使用列表理解来避免 for 循环:

string = "ABCDEYYFGHIAAJKVLMNOPDCQRSTAAVVVUVWXYZ" 
charPositionToFind = 'ADVY' 
target_set = set(charPositionToFind) 
position = [index for index, char in enumerate(string) if char in target_set]