我最近制作了这个程序来模拟随机生成的概念,我的例子是树,但是我不明白为什么我无法在列表中找到随机生成的元素数。我试过了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>
答案 0 :(得分:0)
据我所知,您似乎想要创建一系列随机功能列表。我个人对此的看法是使用随机方法Choice
选择允许我们从列表中选择一个字符串,然后我们使用一个名为.append
的函数,让我们将它包含在另一个列表中
from random import choice
Leaves=["(Pointy ","(Rounded ","(Maple ","(Pine ","(Sticks "]
Trunk=["Oak ","Birch ","Maple ","Ash ","Beech ","Spruce "]
Size=["Extra Large)","Large)","Medium)","Small)","Tiny)"]
Tree=[]
NewCombination = []
while len(Tree)<len(Leaves)*len(Trunk)*len(Size):
NewCombination.append((choice(Leaves)) + (choice(Trunk) + (choice(Size))))
if Tree != NewCombination:
Tree=Tree+NewCombination
print(Tree)
通过在原始三个列表中包含括号和空格,我也更容易看到打印列表