我正在开发一个涉及两个列表的程序:一个是随机顺序中的数字1-5,另一个是仅保存为不同元素的五个单词。基本上我希望能够以第一个列表的随机顺序打印出单词。我试过了:
order = ["2","5","4","1","3"]
words = ["Apple","Boat","Carrot","Dragonfly","Education"]
for i in range (0,5):
print(words[order])
它只是说“TypeError: list indices must be integers, not list
”。
任何人都可以帮助我吗?
答案 0 :(得分:3)
这里有两个问题:
order
的元素,只需将整个列表作为索引传递;和'2'
转换为整数2
。我们可以使用 int(..)
。现在出现了一个新问题:列表具有从零开始的索引,列表中的索引是从一开始的。然而,我们可以从中减去一个。
这导致以下方法:
for i in order:
print(words[int(i)-1])
答案 1 :(得分:2)
更正您的代码将如下所示:
order = ["1","2","3","4","5"]
words = ["Apple","Boat","Carrot","Dragonfly","Education"]
for i in range(0,5):
print(words[int(order[i])])
但这远不是一个干净的解决方案。你正在捣乱index
es太多。
更好的方法是:
for x in order:
print(words[int(x)-1])
所有这一切都说明,你所做的事情没有随机。考虑使用random.shuffle()
。像这样:
from random import shuffle
order = ["1","2","3","4","5"]
words = ["Apple","Boat","Carrot","Dragonfly","Education"]
shuffle(order) # the shuffling is done in-place
for i in [int(c)-1 for c in order]:
print(words[i])
# prints
Carrot
Dragonfly
Education
Boat
Apple
答案 2 :(得分:0)
words = ["Apple","Boat","Carrot","Dragonfly","Education"]
# 1 #
for _ in range(11):
print(words[random.randrange(0, len(words))])
# 2 #
print("Before shuffle: ",words);random.shuffle(words);print("After shuffle: ",words)
# 3 #
print("Choose 1 random sample",random.sample(words, 1))
我不知道你的目标是什么,但这就是我想出的。 此外,您不需要将它们存储为str in' order'名单。您可以拥有一个整数列表,您可以使用它而无需转换。如:order = [1,2,3,4,5]
我希望我的回答很有帮助。欢呼!