【问题标题】:How do I get the index of multiple occurrences of the same character in a string? [duplicate]如何获取字符串中同一字符多次出现的索引? [复制]
【发布时间】:2015-08-09 20:39:27
【问题描述】:

我有这个函数,接收一个单词并列出每个大写字母的索引:

def capitals(word):
    print word
    lst = []
    for i in word:
        if i.isupper():
            lst += [word.index(i)]
    return lst

当单词中的所有大写字母都不同时,它运行正常。示例:

capitals("AuIkkdjsiP") 返回 [0,2,9]

但是,如果字符串有重复的大写字母,就会发生这种情况:

capitals("AuAskdjfIsjUsdhA") 返回 [0,0,10,0]

在迭代字符串时如何获取其他出现的字符“A”的索引?

【问题讨论】:

  • 使用enumerate() 并遍历索引和字符。
  • import re[ match.start() for match in re.finditer('[A-Z]', "AuAskdjfIsjUsdhA") ] ==> 之后[0, 2, 8, 11, 15]

标签: python regex string


【解决方案1】:

您希望enumerate 处理重复字符,也可以使用list comprehension

def capitals(word):
    return [i for i, ch in enumerate(word) if ch.isupper()]

ch 是单词中的每个字符,i 是字符的索引。

另一方面,如果您想将单个项目添加到列表中,则不应附加 +=,如果要添加多个元素,则添加到 +=/extend 是有意义的,但对于单个元素只需附加:

def capitals(word):
    print word
    lst = []
    for i,ch in enumerate(word):
        if ch.isupper():
            lst.append(i)
    return lst

【讨论】:

  • 谢谢,这正是我想要的!
  • 不用担心,不客气,不知道为什么你被否决了,你提供了你的代码和一个很好的尝试。
  • 我见过这种情况,一旦有人将帖子标记为重复,人们甚至不阅读问题就自动开始投票:/
猜你喜欢
  • 2020-04-30
  • 1970-01-01
  • 2021-07-14
  • 2012-02-22
  • 1970-01-01
  • 2010-09-16
  • 1970-01-01
  • 2019-07-14
相关资源
最近更新 更多