2016-07-14 41 views
-8

我最近做了这个程序来模拟随机生成的概念,我的例子是树,但是我不明白为什么我无法在随机生成的数字中找到列表中的元素。我试过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>

+5

问题需要包含足够的信息,以便在问题本身**中可以回答**,而不是在链接后面。图像链接包含在其中 - 就像任何其他链接一样,它们可以打破,我们不希望linkrot使我们的问答数据库的一部分无用。 –

+0

您应该在问题中包含代码(为此,只需在每行代码的前面添加4个空格),以便我们只需复制/粘贴它即可查看它的功能。 –

+1

您可以在编辑器中使用'{}'按钮或[在每行前添加4个空格](https://stackoverflow.com/editing-help#code)在代码块中包含代码片段。 –

回答

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) 

我还通过在原来的三个列表中包含括号和空格来更容易地看到打印列表

相关问题