【问题标题】:How to get index position from a string in python without repetitive results如何在没有重复结果的情况下从python中的字符串获取索引位置
【发布时间】:2019-12-13 12:56:29
【问题描述】:

string 的for 循环中,我想在string 中获取该特定字母的index 位置,但如果该单词中有相同的字母,则它不起作用.

我遍历了 string 中的字母并得到了字母的 index 位置(通过使用 .find().index() )对于由唯一字母组成的 string,但如果 string包含相同的字母,索引只会是出现在string中的第一个字母的位置。

indexList = [] #list of stored indexes
word = "grocery" #could be any string, just using "grocery" as an example
for letter in word:
  index = word.find(letter)
  indexList.append(index)

print (indexList)

#Expected output: [0, 1, 2, 3, 4, 5, 6]
#Actual output: [0, 1, 2, 3, 4, 1, 6]

index 位置的 5 和 1 具有相同的字母(“r”),因此 .find().index() 方法只需添加 1 而不是 5,因为它是 @ 中的第一个“r” 987654336@。我想知道是否有任何方法可以获取指定字母在单词中的位置。请帮忙。谢谢!

【问题讨论】:

  • enumerate 怎么样?
  • 你所描述的相当于range(len(word)),有你想要的用例吗?
  • 是的,我想将所有索引位置保存到名为 positionslist 中,其中嵌套了 lists。然后我想取一组输入的单词,然后取他们的每一个字母,根据它们的索引位置,将它们保存在嵌套的lists中的一个list的位置,然后将它们混在一起做一个品牌新词。
  • 您可以在问题中添加一个示例或打开一个新问题吗?您可以为以上内容返回list(range(len(word)))
  • 感谢您告诉我,但我认为我不应该将其添加到问题中或打开一个新问题,因为您已经回答了。谢谢!

标签: python python-3.x string for-loop indexing


【解决方案1】:

Find 接受两个可选参数:start(默认为 0)和 end(默认为字符串结尾 - 适合您的情况)。使用 enumerate 包含起点:

for i, letter in enumerate(word):
    index = word.find(letter, i)
    indexList.append(index)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-06-02
    • 2021-01-11
    • 2020-12-07
    • 1970-01-01
    • 1970-01-01
    • 2021-02-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多