【发布时间】: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 代码作为代码块。 -
将您的代码作为图像发布会使人们更难提供帮助。
-
请将源代码发布为文本,而不是图像。
-
此外,如果您具体说出问题所在:您想要代码做什么,代码是什么,这将有很大帮助代替,区别是什么。