简体   繁体   中英

How would I parse a result and insert it into a variable?

I'm currently attempting to make a hangman game, whereby you can choose the number of letters in a word.

hLetters = int(input("How many letters? (4-16)\n"))

  def word(letters):
    if letters == 4:
      random.choice(list4)
    if letters == 5:
      random.choice(list5)
    # etc, etc

word(hLetters)

Obviously, this is inefficient - is there a method of getting the value of hLetters to be placed after "list", so that it automatically picks "list4" when the input is 4, or "list8" when the input is 8?

You could place all you lists in a dictionary -

words_lists = {4 : list4, 5: list5}

And choose randomly from this dict values -

random.choice(words_lists[letters])

You could use a list of list for this

letter = 4 
listoflist=[list4,list5,list6,..list16]
print(random.choice(listoflist[letter-4]))

That's a list of lists. Just like you have a list for multiple letters, instead of referring them as letter1, letter2, make a lists of you multiple lists

 outer_list = [list1, list2, ...]

and then

random.choice(outer_list[letter - 1])

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