代码之家  ›  专栏  ›  技术社区  ›  user7579444

在Python中,如何获取相同字符的数量及其在字符串中的位置?

  •  0
  • user7579444  · 技术社区  · 7 年前

    我有一个字符串、列表和起始位置:

    s = "NNDRJGLDFDNJASNJBSA82NNNNNDHDWUEB3J4JJX"
    l = [0, ""]
    start = 0
    

    现在我想提取所有N及其在字符串中的位置。到目前为止,我尝试的是:

    for i in range(len(s)):
        if s[i] == "N":
            l[0] = i+start
            l[1] = s[i]
    

    但我只从字符串中获取最后一个“N”字符。有什么建议吗?

    3 回复  |  直到 7 年前
        1
  •  3
  •   mhawke    7 年前

    你可以将列表理解与 enumerate() 要获取每个目标角色的索引,请执行以下操作:

    s = "NNDRJGLDFDNJASNJBSA82NNNNNDHDWUEB3J4JJX"
    positions = [i for i,c in enumerate(s) if c == 'N']
    >>> positions
    [0, 1, 10, 14, 21, 22, 23, 24, 25]
    
        2
  •  0
  •   kabanus    7 年前

    使用索引方法的另一种方法:

    indices = []
    try:
        start = 0
        while True:
            indices.append(s.index('N',start))
            start = indices[-1]+1
    except ValueError: pass
    

    使用numpy的解决方案:

    from numpy import array,where
    print(where(array(list(s))==N))
    

    修复您自己的解决方案:

    for i in range(len(s)):
        if s[i] == "N":
            indices.append(i)
            indices.append(s[i])
    

    你不需要开始,我建议你不要使用 list 作为变量名。

        3
  •  0
  •   Reblochon Masque    7 年前

    如果枚举列表,则可以检索存在 N :

        s = "NNDRJGLDFDNJASNJBSA82NNNNNDHDWUEB3J4JJX"
        indices = []
        start = 0
    
        for idx, c in enumerate(s):
            if c == "N":
                indices.append(idx)
        indices 
    

    输出:

    [0, 1, 10, 14, 21, 22, 23, 24, 25]