[英]Python - Random.sample from a range with excluded values (array)
I am currently using the random.sample function to extract individuals from a population.我目前正在使用 random.sample function 从人群中提取个体。
ex:前任:
n = range(1,1501) n = 范围 (1,1501)
result = random.sample(n, 500) print(result)结果 = random.sample(n, 500) 打印(结果)
in this example I draw 500 persons among 1500. So far, so good..在这个例子中,我在 1500 人中画了 500 人。到目前为止,还不错。
Now, I want to go further and launch a search with a list of exclude people.现在,我想进一步拨打 go 并使用排除人员列表启动搜索。
exclude = [122,506,1100,56,76,1301]排除 = [122,506,1100,56,76,1301]
So I want to get a list of people (1494 persons) while excluding this array (exclude)所以我想得到一个人的列表(1494 人)同时排除这个数组(排除)
I must confess that I am stuck on this question.我必须承认我被困在这个问题上。 Do you have an idea?
你有好主意吗? thank you in advance!
先感谢您!
I am learning Python language.我正在学习 Python 语言。 I do a lot of exercise to train.
我做了很多运动来训练。 Nevertheless I block ue on this one.
不过我在这个上屏蔽了ue。
exclude = {122, 506, 1100, 56, 76, 1301}
result = random.sample([k for k in range(1, 1501) if k not in exclude], 500)
# check
assert set(result).isdisjoint(exclude)
Marginally faster (but a bit more convoluted for my taste):稍微快一点(但对我来说有点复杂):
result = random.sample(list(set(range(1, 1501)).difference(exclude)), 500)
import random
exclude = {1, 6}
result = random.sample(list(set(range(1, 21)).difference(exclude)), 18)
print(result)
Thank you for your reply.感谢你的回复。 It works perfectly with this example!
它与这个例子完美搭配!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.