简体   繁体   English

如何更改列表中的内容

[英]How to change things in lists

import random
word_list = ["aardvark", "baboon", "camel"]
chosen_word = random.choice(word_list)

guess = input("Guess a letter: ").lower()

display = []
chosen_word_length = len(chosen_word)
for length in range(chosen_word_length):
  display.append("_")
print(display)

I am trying to make a hangman game but the thing I'm struggling on is when the player guesses a letter that is in the word how to I insert that letter in the correct place in "display".我正在尝试制作一个刽子手游戏,但我正在努力的事情是当玩家猜测单词中的一个字母时,我如何将该字母插入“显示”中的正确位置。

I'm really struggling on this and help would be greatly appreciated.我真的在努力解决这个问题,我们将不胜感激。

I would propose implementing a set that stores all letters which are already know.我建议实施一个集合来存储所有已知的字母。

Your diplaying would then look like this:你的 diplaying 看起来像这样:

# known_letters is a set holding all letters that player guessed
display = ["_"] * len(chosen_word)
for i in range (len(chosen_word)):
   if chosen_word[i] in known_letters:
      display[i] = chosen_word[i]

print(display)

The word is "baboon" and you have这个词是“狒狒”,你有

display = ['_', '_', '_', '_', '_', '_']

And want to make it并且想要成功

display = ['b', '_', 'b', '_', '_', '_']

You could loop over "baboon" and display and check if the current letter is the same.您可以遍历“baboon”并display并检查当前字母是否相同。 If it is, you replace the underscore with the letter.如果是,则用字母替换下划线。 If it isn't, you leave the underscore.如果不是,则保留下划线。

You'll find it useful to look at these functions that make it easy to deal with lists and other "iterables."您会发现查看这些使处理列表和其他“可迭代对象”变得容易的函数很有用。

  • enumerate : used here to loop over an index and element of an iterable at the same time. enumerate :在这里用于同时遍历可迭代的索引和元素。
  • zip : used here to loop over two iterables ( word and display ) at the same time. zip :此处用于同时循环两个可迭代对象( worddisplay )。
display = ['_', '_', '_', '_', '_', '_']

guess_letter = 'b'
word = 'baboon'

for index, (display_character, word_character) in enumerate(zip(display, word)):
    if guess_letter == word_character:
        display[index] = guess_letter

print(display)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM