gpt4 book ai didi

python - 如何创建一个函数来查找列表中单词的索引?

转载 作者:太空宇宙 更新时间:2023-11-04 00:38:03 25 4
gpt4 key购买 nike

我正在尝试扩展我的刽子手游戏,以便您能够选择您希望单词的字母数量。我将通过使用选择方法(例如 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com