【问题标题】:How to find the indexes of all occerences of a character in a string? [duplicate]如何查找字符串中所有出现的字符的索引? [复制]
【发布时间】:2019-12-10 02:10:17
【问题描述】:

我想标题是不言自明的,不过,我会让自己更清楚。

我必须找到字符串中每个字符的索引。例如,

word = "banana"
def indexes(x, word):
    #some code
    return (list of indexes of x character in the word)

输出:

indexes('a', word)
>> [1, 3, 5]

我如何得到这个结果?

【问题讨论】:

    标签: python string list indexing


    【解决方案1】:

    试试这个:

    word = "banana"
    def indexes(x, word):
        output = []
        for i,y in enumerate(word):
            if x == y:
                output.append(i)
        return output
    
    output = indexes("a", word)
    print(output)
    

    【讨论】:

    • 非常感谢您对我的帮助。您的代码肯定有效。但是当他首先回答时,我必须将其他人的解决方案标记为绿色。再次感谢您。
    【解决方案2】:

    使用列表推导

    • enumerate() - 方法向一个可迭代对象添加一个计数器,并以枚举对象的形式返回它。

    例如

    word = "banana"
    indexes = [ index for index,x in enumerate(word) if x in 'a' ]
    print(indexes)
    

    O/P:

    [1, 3, 5]
    

    【讨论】:

    • x == 'a'
    • 非常感谢你。万分感激。它有效!
    • @ParthikB。 python中in==运算符see this的行为。
    • @ParthikB。不客气
    【解决方案3】:

    我会做这样的事情

    word = "banana"
    def indexes(x, word):
      result = []
      for idx, letter in enumerate(word):
        if letter == x:
          result.append(idx)
      return result
    

    然后

    indexes('a', word)
    [1, 3, 5]
    

    【讨论】:

      猜你喜欢
      • 2012-11-15
      • 2016-05-13
      • 2012-10-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多