[英]How to remove a random element from a list and add it to another list in python
list = ['john','james','michael','david','william']
winner = []
如何从list
删除随机项并将其添加到winner
?
winner.append(list.pop(random.randrange(0,len(list))))
To break this down: 打破这个:
random.randrange(0,len(list))
will generate a random number between zero and the length of your list inclusive. 将生成一个介于零和列表长度之间的随机数。 This will generate a random index in your list that you can reference.
这将在列表中生成您可以引用的随机索引。
list.pop(i)
This will remove the item at the specified index (i) from your list. 这将从列表中删除指定索引(i)处的项目。
winner.append(x)
This will add an item (x) to the end of the winner list. 这会将项目(x)添加到获胜者列表的末尾。 If you want to add the item at a specific index, you can use
如果要在特定索引处添加项目,可以使用
winner.insert(i,x)
with i being the index to insert at and x being the value to insert. i是插入的索引,x是要插入的值。
If you want more information, a good reference is the python docs on data structures: https://docs.python.org/2/tutorial/datastructures.html 如果您想了解更多信息,可以参考数据结构的python文档: https : //docs.python.org/2/tutorial/datastructures.html
This selects a random item from a list of names names
and adds it to another list winner
. 这从名称的列表中选择一个随机的项目
names
,并将其添加到另一个列表winner
。 The chosen winner is then removed from the names
. 然后从
names
删除所选的获胜者。
import random
winner = []
names = ['john','james','michael','david','william']
winnerindex = random.randint(0,len(names)-1)
winner.append(names[winnerindex])
del names[winnerindex]
print winner, names
Simply use random.randint from index 0 to len(list) to get the index of the element of list and append it to winner. 只需使用从索引0到len(list)的random.randint来获取列表元素的索引并将其追加到胜利者。
import random
index = random.randomint(0, len(list)-1)
winner.append(list[index])
del list[index]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.