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

标签 python python-3.x

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

相关文章:

python - str.isdecimal() 和 str.isdigit() 区别示例

python - 支持 ANSI/VT100 的 AJAX 控制台窗口?

python - Pandas 读取具有浮点值的 csv 文件导致奇怪的舍入和小数位

Python。 from dateutil.relativedelta import * 在 shell 中有效,但在脚本中无效

python - Python 3.2 中的外来字符

python-3.x - 根据 flask 中的其他选择选项显示选择字段

python - 如何在google-colaboratory上安装需要编译的库

python - 找不到 Graphviz 的可执行文件(Python 3.4)

python - Tensorflow 对象检测培训最佳实践问题

python - 使用分区计算 Pandas 中条目之间的增量