我是编程的新手,我想将随机选择的单词附加到单独的字母列表中(letterList)
import random
wordList = ["bird", "dog", "cat", "school", "computer"]
underscoreList = []
letterList = []
word = random.choice(wordList)
for letter in word:
letterList.append[letter]
underscoreList.append["_"]
你的代码大部分都很好,当你想要括号(用于函数/方法调用)时,你只是滥用方括号(用于索引/查找)。 append
是list
上的一个方法,所以你需要用括号分隔参数,改变:
letterList.append[letter]
underscoreList.append["_"]
至:
letterList.append(letter)
underscoreList.append("_")
请注意,在这种特殊情况下,你可以简化很多,用简单的转换为list
和list
乘法代替你的循环(以及你的list
s的初始定义),只留下:
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
它附加(信件)不附加[信件]
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)