我正在尝试扩展我的刽子手游戏,以便您能够选择您想要的单词的字母数量。我将通过使用选择方法(例如 if,else)来完成此操作,但是在创建该函数后,我遇到了一个错误,因此在找到错误的来源并开始解决错误后,我丢弃了整个函数。基本上我试图使用index()函数来定位元素所在的位置,但由于某种原因它不起作用它总是输出0。
def wordLength(word):
r = word
num=word.index(r)
print(num)
最佳答案
我认为您想要实现的目标是这样的(因为您提到您在问题的评论中使用了 .split()
:
sentence = "this is a sentence"
sentence_split = sentence.split()
def wordLength(word, sentence):
try:
index = sentence.index(word)
print(index)
except:
print("word not in sentence")
wordLength("a", sentence_split)
结果为“3”,即“a”在句子中的位置。
编辑
或者,如果您想要每个单词中每个字母的索引号..
sentence = "this is a sentence"
sentence_split = sentence.split()
letter_index = []
def index_letters():
for i in sentence_split:
# I results in "this" (1st loop), "is" (2nd loop), etc.
for x in range(len(i)):
# loops over every word, and then counts every letter. So within the i='this' loop this will result in four loops (since "this" has 4 letters) in which x = 0 (first loop), 1 (second loop), etc.
letter = i[x]
index = i.index(letter)
letter_index.append([index, letter])
return letter_index
print(index_letters())
结果为:[[0, 't'], [1, 'h'], [2, 'i'], [3, 's'], [0, 'i'], [1, 's'], [0, 'a'], [0, 's'], [1, 'e'], [2, 'n'], [3, 't'], [1, 'e' '], [2, 'n'], [6, 'c'], [1, 'e']]
关于python - 如何创建一个函数来查找列表中单词的索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43009038/