Py学习  »  Python

如何在python的列表中找到输入的位置[副本]

scarab • 4 年前 • 975 次点击  

我现在正在构建一个简单的刽子手游戏,我希望能够识别用户在列表中猜测特定字母的位置例如,如果单词列表是[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!')
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/49240
 
975 次点击  
文章 [ 3 ]  |  最新文章 4 年前
C.Nivs
Reply   •   1 楼
C.Nivs    4 年前

更快的替代方案 list.index 你可以建造一个 dictionary of letter:索引对使用 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!")

对于短名单, 列表索引 完全没问题,你不会注意到 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

注意,对于大量的项目, 迪克特 规模真的很好

Ayoub Benayache
Reply   •   2 楼
Ayoub Benayache    4 年前
# 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)))
Anthony Kong
Reply   •   3 楼
Anthony Kong    4 年前

你可以使用 index 列表的功能

例如

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

但是如果猜测不在列表中,你会得到一个 ValueError . 你需要处理这个异常。