Tuple index

Steve M steve at myplace.com
Mon Feb 21 17:31:17 EST 2005


Steven Bethard wrote:

> Steve M wrote:
>> I'm actually doing this as part of an exercise from a book. What the
>> program is supposed to do is be a word guessing game. The program
>> automaticly randomly selects a word from a tuple. You then have the
>> oportunity to ask for a hint. I created another tuple of hints, where the
>> order of the hints correspond to the word order. I was thinking if I
>> could get the index position of the randomly selected word, I pass that
>> to the hints tuple to display the correct hint from the hints tuple. I'm
>> trying to do it this way as the book I'm using has not gotten to lists
>> yet.
> 
> I'm guessing it also hasn't gotten to dicts yet either?  Perhaps a
> somewhat more natural way of doing this would be something like:
> 
> py> hints = dict(word1="here's hint 1!",
> ...              word2="here's hint 2!",
> ...              word3="here's hint 3!")
> py> words = list(hints)
> py> import random
> py> selected_word = random.choice(words)
> py> selected_word
> 'word3'
> py> print hints[selected_word]
> here's hint 3!
> 
> That said, if you want to find the index of a word in a tuple without
> using list methods, here are a couple of possibilities, hopefully one of
> which matches the constructs you've seen so far:
> 
> py> t = ("fred", "barney", "foo")
> 
> py> for i, word in enumerate(t):
> ...     if word == "barney":
> ...         break
> ...
> py> i
> 1
> 
> py> for i in range(len(t)):
> ...     if t[i] == "barney":
> ...         break
> ...
> py> i
> 1
> 
> py> i = 0
> py> for word in t:
> ...     if word == "barney":
> ...         break
> ...     i += 1
> ...
> py> i
> 1
> 
> HTH,
> 
> STeVe

Thanks Steve, I'll see if I can make that solution work for me.

Steve



More information about the Python-list mailing list