我最近做了这个程序来模拟随机生成的概念,我的例子是树,但是我不明白为什么我不能在列表中找到一个随机生成的数字元素。我试过Leaves.index()
,但似乎不起作用。有没有什么方法可以从我的一个列表中随机抽取一个字符串并将其添加到另一个列表中?你知道吗
import random
Leaves=["Pointy","Rounded","Maple","Pine","Sticks"]
Trunk=["Oak","Birch","Maple","Ash","Beech","Spruce"]
Size=["Extra Large","Large","Medium","Small","Tiny"]
Tree=[]
while len(Tree)<len(Leaves)*len(Trunk)*len(Size):
NewCombination=Leaves.index(random.randrange(len(Leaves)))+Trunk.index(random.randrange(len(Trunk)))+Size.index(random.randrange(len(Size)))
if Tree != NewCombination:
Tree=Tree+NewCombination
print(Tree)
错误:
Traceback (most recent call last):
File "C:/Users/invis_000/Documents/Coding/Python/Generation.py", line 8, in <module>
据我所知,似乎你想创建一个由一堆随机特征组成的列表。我个人的做法是使用随机方法
Choice
Choice允许我们从一个列表中选择一个字符串,然后我们使用一个名为
.append
的函数将它包含在另一个列表中我还通过在您原来的三个列表中添加括号和空格,使打印的列表更容易查看
相关问题 更多 >
编程相关推荐