如何在python的列表中查找输入出现的位置?

时间:2019-06-05 00:10:11

标签: python python-3.x

我现在正在构建一个简单的子手游戏,我希望能够识别出用户在列表中猜到了特定字母的位置。例如,如果单词列表是[D,R,A,G,O,N]-并且用户猜到了A,我希望能够得到表示4的返回值...这是我失败的代码到目前为止

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!')

3 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

您可以使用列表的index功能

例如

>>> word_list.index('white')
2

但是如果猜测不在列表中,您将得到ValueError。您需要处理此异常。

答案 2 :(得分:0)

list.index的另一种更快的替代方法是,您可以使用dictionary来构建字母对:enumerate

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的缩放比例确实很好