【问题标题】:Getting positions for set of characters in a python string获取python字符串中字符集的位置
【发布时间】:2012-10-22 19:55:03
【问题描述】:

获取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]

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

【问题讨论】:

    标签: python string python-2.7


    【解决方案1】:

    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]
    

    【讨论】:

      【解决方案2】:

      如果您需要所有匹配项:

      import re
      
      text = "ABCDEYYFGHIAAJKVLMNOPDCQRSTAAVVVUVWXYZ"
      chars = "ADVY"
      positions = [m.start() for m in re.finditer("|".join(map(re.escape, chars)), text)]
      print(positions)
      

      Output

      [0, 3, 5, 6, 11, 12, 15, 21, 27, 28, 29, 30, 31, 33, 36]
      

      【讨论】:

        猜你喜欢
        • 2017-09-30
        • 1970-01-01
        • 2019-12-10
        • 1970-01-01
        • 1970-01-01
        • 2023-03-18
        • 1970-01-01
        • 2014-06-23
        • 1970-01-01
        相关资源
        最近更新 更多