如何从列表中随机选择一个字符串,并将其插入到新列表中?

2024-04-18 12:17:50 发布

您现在位置:Python中文网/ 问答频道 /正文

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


Tags: 程序tree概念列表sizeindexlenrandom
1条回答
网友
1楼 · 发布于 2024-04-18 12:17:50

据我所知,似乎你想创建一个由一堆随机特征组成的列表。我个人的做法是使用随机方法Choice

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)

我还通过在您原来的三个列表中添加括号和空格,使打印的列表更容易查看

相关问题 更多 >