简体   繁体   中英

How to create a function that finds the index of a word in a list?

I'm trying to extend my hangman game so that your able to select the amount of letters you want your word to be. I'll do this by using the selection method (eg if,else) however after making the function i come across an error so i scarped the hole function after finding where the error came from and started working on solving the error. Basically I'm trying to use index() function to locate where the element is but for some reason it doesn't work it always outputs 0.

def wordLength(word):
    r = word
    num=word.index(r)
    print(num)

I think what you are trying to achieve is this (since you mentioned you used .split() in the comments on your question:

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)

Results in '3', which is the position of 'a' within your sentence.

EDIT

Or, if you want the index number of each letter within each word..

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())

Results in: [[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']]

If I understand what you are asking then you should be able to take the word chosen for the hangman game and create a list of every letter in the word then finding the index() of the letter in the list.

Without the question being more clear it seams like you are asking for the index of a letter in a word. What I have for that is below.

something like this should help:

hm_word = []   #the list to be created for the given word

def wordlist(hangman_word): #Creates a list of each letter of the word
    for letter in hangman_word:  
        hm_word.append(letter)  

wordlist("bacon")# calls the function and puts in the word chosen

print (hm_word) #just to show the list has been created
print (hm_word.index("o")+1) #This prints the index of the letter 'o' however you can use a user input here.
#NOTE: I used +1 in the print for the index to show the index number starting from 1 not 0

you can use this as a starting point to get the index of the letter being guessed by taking the user input and placing it in the index(). I only used "o" as an example of how it works.

def find_word(word, word_list):
    try:
        return word_list.index(word)
    except ValueError:
        return None    # or what ever you need

>>> word_list = ['bubble', 'lizzard', 'fish']
>>> find_word('lizzard', word_list)
1
>>> print(find_word('blizzard', word_list))
None

It's returning 0, because you are running index on the input variable for itself. You will need to index on a segment of the input variable. A slight modification of your example, that will return something other than 0:

def wordLength(word):
    r = 'r'
    num=word.index(r)
    print(num)

This should print the number 2.

"wordLength" is a bit of a misnomer here for your function. If you want the length of a word, you can just do: len(word)

def findChar(word, char):
    # don't go any further if they aren't strings
    assert isinstance(word, basestring)
    assert isinstance(char, basestring)
    # return the character you are looking for,
    # in human friendly form (1 more than the python index)
    return word.lower().index(char.lower()) + 1

to use:

>>>print findChar('heat', 'a')
3   # a is in the third position.

This does not address a single character being in a word many times, obviously.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM