【发布时间】: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)),有你想要的用例吗? -
是的,我想将所有索引位置保存到名为
positions的list中,其中嵌套了lists。然后我想取一组输入的单词,然后取他们的每一个字母,根据它们的索引位置,将它们保存在嵌套的lists中的一个list的位置,然后将它们混在一起做一个品牌新词。 -
您可以在问题中添加一个示例或打开一个新问题吗?您可以为以上内容返回
list(range(len(word))) -
感谢您告诉我,但我认为我不应该将其添加到问题中或打开一个新问题,因为您已经回答了。谢谢!
标签: python python-3.x string for-loop indexing