需要帮助在列表中将单词作为单独的字母附加

问题描述 投票:0回答:3

我是编程的新手,我想将随机选择的单词附加到单独的字母列表中(letterList)

import random
wordList = ["bird", "dog", "cat", "school", "computer"]
underscoreList = []
letterList = []

word = random.choice(wordList)

for letter in word:
  letterList.append[letter]
  underscoreList.append["_"]
python python-3.x append
3个回答
0
投票

你的代码大部分都很好,当你想要括号(用于函数/方法调用)时,你只是滥用方括号(用于索引/查找)。 appendlist上的一个方法,所以你需要用括号分隔参数,改变:

letterList.append[letter]
underscoreList.append["_"]

至:

letterList.append(letter)
underscoreList.append("_")

请注意,在这种特殊情况下,你可以简化很多,用简单的转换为listlist乘法代替你的循环(以及你的lists的初始定义),只留下:

import random
wordList = ["bird", "dog", "cat", "school", "computer"]

word = random.choice(wordList)

letterList = list(word)  # Converts to list of characters directly
underscoreList = ['_'] * len(word)  # Makes list of underscores of matching length

-1
投票

它附加(信件)不附加[信件]


-1
投票
import random 
wordList = ["bird", "dog", "cat", "school", "computer"] 
underscoreList = [] 
letterList = []
for x in range(3):
    word = random.choice(wordList)
    letterList += [[x for x in word]]
    for letter in word:
        underscoreList.append("_")
print(letterList)
© www.soinside.com 2019 - 2024. All rights reserved.