【问题标题】:how to select a word in list by its index in python如何通过python中的索引选择列表中的单词
【发布时间】:2016-04-09 12:01:55
【问题描述】:
import random
print('Welcome to the Guess-The-Word Game.')
print('Password is one of the words:')

wordList = ['AETHER', 'BADGED', 'BALDER', 'BANDED', 'BANTER', 'BARBER', 'BASHER', 'BATHED']

for index,word in enumerate(wordList):
print(index , '-', word)

password =(random.choice(wordList))

guess = None
counter = 0
while guess !=  password:
    guess = input('enter your guess:')
    counter = counter + 1

    if counter ==4:
    print('Game over')

    elif guess == password:
    print(password, ' is correct')

    else:
    print('wrong guess try again')

在代码中,用户直接输入猜测词。有什么方法可以让用户输入猜测作为单词的索引,而不是完全输入完整的单词。

【问题讨论】:

  • 是的,有。您有真正的问题吗?
  • 这里是 Python 3.x 数据结构的文档docs.python.org/3.1/tutorial/datastructures.html
  • 我是 python 新手。你能告诉它是如何实现的吗??
  • 只需使用my_list_variable[item_index]

标签: list python-3.x indexing


【解决方案1】:

试试这个希望你正在尝试这个:

import random
print('Welcome to the Guess-The-Word Game.')
print('Password is one of the words:')

wordList = ['AETHER', 'BADGED', 'BALDER', 'BANDED', 'BANTER', 'BARBER', 'BASHER', 'BATHED']

status_flag = False
guess = None
counter = 0
password =(random.choice(wordList))
word_index = wordList.index(password)
max_index = len(wordList)-1

while guess !=  password:
    guess = input('Enter your guess:[0 -'+str(max_index)+']')
    if guess > max_index:
        print ('Wrong input: Enter your guess:[0 -'+str(max_index)+']')
        continue

    counter = counter + 1
    if counter ==4:
        print('Game over')
        status_flag = True

    elif guess == word_index:
        print(str(password)+' is correct')
        status_flag = True

    else:
        print('Wrong guess try again')

    if status_flag:
        break

【讨论】:

    猜你喜欢
    • 2014-07-08
    • 1970-01-01
    • 2021-11-08
    • 2021-06-18
    • 2018-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多