我现在正在构建一个简单的绞刑者游戏,我希望能够识别出用户在列表中的哪个位置猜到了特定的字母。例如,如果单词列表是D,R,A,G,O,N --用户猜测A,我希望能够得到一个返回值,说明4...this是我迄今为止失败的代码
import random
word_list = ['red', 'better', 'white', 'orange', 'time']
hidden_list = []
selected_word = random.choice(word_list)
letters = len(selected_word)
selected_word_list = list(selected_word)
game_playing = True
print('My word has ' + str(letters) + ' letter(s).')
print(selected_word_list)
for i in selected_word_list:
hidden_list.append('_')
while game_playing:
print(hidden_list)
guess = input('What letter do you want to guess?')
if guess in selected_word_list:
print('Nice guess!')
else:
print('Nope!')
发布于 2019-06-05 08:16:51
您可以使用列表的index
函数
例如:
>>> word_list.index('white')
2
但如果猜测不在列表中,您将得到一个ValueError
。您需要处理此异常。
发布于 2019-06-05 08:15:38
# vowels list
vowels = ['a', 'e', 'i', 'o', 'i', 'u']
# index of i item is printed
for i in vowels:
print('The index of:', i+" "+str(vowels.index(i)))
发布于 2019-06-05 08:18:30
list.index
的另一种更快的替代方法是,您可以使用enumerate
构造一个由dictionary
:index对组成的字母
yourlist = list('DRAGON')
yourdict = {letter: idx for idx, letter in enumerate(yourlist)}
guess = input('What letter do you want to guess?')
result = yourdict.get(guess.strip()) # Avoids KeyError on missing letters
if result is not None:
print("You got it!", result)
else:
print("Nope!")
对于短列表,list.index
完全没问题,您不会注意到dict
的性能提升,但对于非常长的列表,它会有很大的不同:
短名单
列表
python -m timeit -s 'x = list(range(50))' 'x.index(49)'
1000000 loops, best of 3: 0.584 usec per loop
字典
python -m timeit -s 'x = dict(enumerate(list(range(50))))' 'x.get(49)'
10000000 loops, best of 3: 0.0733 usec per loop
# at this level, you really won't notice the difference on a GHz processor
长列表
列表
python -m timeit -s 'x = list(range(500000))' 'x.index(490000)'
100 loops, best of 3: 4.91 msec per loop
字典
python -m timeit -s 'x = dict(enumerate(list(range(500000))))' 'x.get(490000)'
10000000 loops, best of 3: 0.0884 usec per loop
请注意,对于大量项目,dict
的伸缩性非常好
https://stackoverflow.com/questions/56452784
复制相似问题