Random Sample with remove from List

末鹿安然 提交于 2020-01-12 08:01:12

问题


I have data in a list like:

L = [(3,4,5),(1,4,5),(1,2,3),(1,2,3)]

I need to sample randomly a size of 2 so I wanted to use:

import random
t1 = random.sample(set(L),2)

Now T1 is a List of the randomly pulled values, But i wanted to remove those randomly pulled from our initial list from our initial list. I could do a linear for loop but for the task I'm trying to do this for a larger list. so the Run time would take for ever!

Any suggestions on how to go about this?


回答1:


t1 = [L.pop(random.randrange(len(L))) for _ in xrange(2)]

doesn't change the order of the remaining elements in L.




回答2:


One option is to shufle the list and then pop the first two elements.

import random
L = [(3,4,5),(1,4,5),(1,2,3),(1,2,3)]
random.shuffle(L)
t1 = L[0:2]


来源:https://stackoverflow.com/questions/16477158/random-sample-with-remove-from-list

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!