简体   繁体   English

如何从列表中删除随机元素并将其添加到python中的另一个列表中

[英]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.

相关问题 从列表中删除元素并添加到另一个 - Remove element from list and add to another 如何从 python 列表中的随机元素 select - How to select random element from a list in python 根据来自另一个列表的匹配从 python 列表中删除元素 - remove element from python list based on match from another list 如果存在于另一个列表中,python从嵌套列表中删除该元素+ - python remove element from nested list if it exists in another list + 从列表元素中删除模式并在 Python 中返回另一个列表 - Remove a pattern from list element and return another list in Python 如何从python中的列表列表中删除列表元素 - How to remove list element from list of list in python Python - 从作为另一个元素的子字符串的字符串列表中删除任何元素 - Python - Remove any element from a list of strings that is a substring of another element Python:如何为列表的每个元素添加另一个列表中的每个元素? - Python : How to add for each element of a list every element from another list? 如果列表 Python 中存在元素,如何从列表中删除元素 - How to remove element from list if element is present in list Python 如何从列表中删除所有元素,该列表是 python 中同一列表中另一个更大元素的子序列? - How do I remove all elements from a list which is a subsequence of another bigger element in the same list in python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM