【问题标题】:How to randomly pick a string from a list, and insert it into a new one? [closed]如何从列表中随机选择一个字符串,并将其插入一个新字符串? [关闭]
【发布时间】:2016-11-17 16:26:51
【问题描述】:

此代码分解了一种在列表中选择随机元素并将其插入新元素的方法。

希望这比原来的问题更能说明问题,因为我试图解释每一行代码

#Allows us to use randrange specifically
from random import randrange

#Our list of objects to pick from
objectList = ["Box","Table","Chair","Bed"]
#The empty list we are adding to
emptyList = []

#Find out how many objects are in the list
numObjects = len(objectList) # Will return 4

#Pick a random number between 0 and numObjects - 1
randomIndex = randrange(numObjects)

#Select and store an object at the randomIndex in objectList

#If randomIndex = 2, the selectedObject would be "Chair"
#as the first index is 0
#"Box"   - index 0
#"Table" - index 1
#"Chair" - index 2
#"Bed"   - index 3
selectedObject = objectList[randomIndex]

#Add the object to the empty list
emptyList.append(selectedObject)

#To simplify picking the random object you should use this
selectedObject = objectList[randrange(len(objectList))]
emptyList.append(selectedObject)

#Or furthermore
emptyList.append(objectList[randrange(len(objectList))])

【问题讨论】:

  • 问题需要包含足够的信息才能在问题本身中回答,而不是在链接后面。图片链接包含在其中 - 与任何其他链接一样,它们可能会中断,我们不希望 linkrot 使我们的问答数据库的某些部分变得无用。
  • 您可以使用编辑器中的{} 按钮或adding 4 spaces before each line 在帖子中包含sn-ps 代码作为代码块。
  • 将您的代码作为图像发布会使人们更难提供帮助。
  • 请将源代码发布为文本,而不是图像。
  • 此外,如果您具体说出问题所在:您想要代码做什么,代码是什么,这将有很大帮助代替区别是什么。

标签: python list random


【解决方案1】:

据我所知,您似乎想创建一个包含一堆随机特征的列表。我个人的方法是使用随机方法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)

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-02-07
    • 1970-01-01
    • 2012-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-04
    • 1970-01-01
    相关资源
    最近更新 更多