简体   繁体   English

算法从列表中访问两个随机元素,将它们存储在变量中并从 Python 3.x 中的原始列表中删除元素?

[英]Algorithim to access two random elements from a list, store them in a variable and delete the elements from the original list in Python 3.x?

I have a list, that so far has 4 elements.我有一个列表,到目前为止有 4 个元素。 I can use the random.sample command to pick 2 elements at random我可以使用 random.sample 命令随机选择 2 个元素

teamslist = "apple" , "banana" , "orange", "clementines"
teamrandom = random.sample(teamslist, k = 2)

Is there anyway for the randomly picked elements stored in teamrandom, to be removed from list "teamlist", so that only the remaining 2 strings are left in the list?无论如何,存储在teamrandom中的随机选择的元素是否要从列表“teamlist”中删除,以便列表中只剩下剩余的2个字符串?

This way, when the command is run again, it only picks the 2 remaining elements from the list?这样,当命令再次运行时,它只从列表中选择剩余的 2 个元素?

No element should be chosen more than once不得多次选择任何元素

You can simply use random.shuffle to shuffle the list(change the order of its elements) and then pop an element from it each time you need a random one:您可以简单地使用random.shuffle来打乱列表(更改其元素的顺序),然后在每次需要随机元素时从中弹出一个元素:

import random
teamslist = ["apple" , "banana" , "orange", "clementines"]
random.shuffle(teamslist)

and when you want a random element当你想要一个随机元素时

element = teamslist.pop()

Note: list.pop() returns the last element after removing it from a list注意: list.pop()返回从列表中删除后的最后一个元素

EDIT:编辑:

As stated in the comments, this will lose the order in the original list.如评论中所述,这将丢失原始列表中的顺序。 So a simple fix would be:所以一个简单的解决方法是:

import random
teamslist = ["apple" , "banana" , "orange", "clementines"]
shuffled = teamslist.copy()
random.shuffle(shuffled)

and then to take a new element, just use the same syntax:然后获取一个新元素,只需使用相同的语法:

element = shuffled.pop()

pop() a random index in the list and store in a new list: pop()列表中的随机索引并存储在新列表中:


import random

teamslist = ["apple" , "banana" , "orange", "clementines"]

teamsrandom = [teamslist.pop(random.randint(0, len(teamslist) - 1)) for _ in range(2)]

print(teamsrandom)
print(teamslist)

Output: Output:

['clementines', 'orange']
['apple', 'banana']

You can use randint and pop :您可以使用randintpop

from random import randint
teamslist = ["apple" , "banana" , "orange", "clementines"]
teamrandom = [teamslist.pop(randint(0,len(teamslist)-1)),
              teamslist.pop(randint(0,len(teamslist)-1))]

print(teamslist)
print(teamrandom)

Output: Output:

['banana', 'clementines']
['apple', 'orange']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM