首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在python中查找列表中出现输入的位置?

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

Stack Overflow用户
提问于 2019-06-05 08:10:11
回答 3查看 51关注 0票数 -2

我现在正在构建一个简单的绞刑者游戏,我希望能够识别出用户在列表中的哪个位置猜到了特定的字母。例如,如果单词列表是D,R,A,G,O,N --用户猜测A,我希望能够得到一个返回值,说明4...this是我迄今为止失败的代码

代码语言:javascript
复制
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!')
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2019-06-05 08:16:51

您可以使用列表的index函数

例如:

代码语言:javascript
复制
>>> word_list.index('white')
2

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

票数 0
EN

Stack Overflow用户

发布于 2019-06-05 08:15:38

代码语言:javascript
复制
# 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)))
票数 0
EN

Stack Overflow用户

发布于 2019-06-05 08:18:30

list.index的另一种更快的替代方法是,您可以使用enumerate构造一个由dictionary:index对组成的字母

代码语言:javascript
复制
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的性能提升,但对于非常长的列表,它会有很大的不同:

短名单

列表

代码语言:javascript
复制
python -m timeit -s 'x = list(range(50))' 'x.index(49)'
1000000 loops, best of 3: 0.584 usec per loop

字典

代码语言:javascript
复制
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 

长列表

列表

代码语言:javascript
复制
python -m timeit -s 'x = list(range(500000))' 'x.index(490000)'
100 loops, best of 3: 4.91 msec per loop

字典

代码语言:javascript
复制
python -m timeit -s 'x = dict(enumerate(list(range(500000))))' 'x.get(490000)'
10000000 loops, best of 3: 0.0884 usec per loop

请注意,对于大量项目,dict的伸缩性非常好

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56452784

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档