随机选择2个数字,最小差异为5

问题描述 投票:1回答:1

我有一个正在运行的数字列表,我试图在列表中随机选择2个数字,同时确保这两个数字之间的差异大于5.此外,所选的数字不能是第一个或最后5个数字。输入列表。

我写了这段代码,但效果不好。

_list = random.sample(range(5, len(_det)-5), 2)

if max(_list) - min(_list) < 5:
    _list = random.sample(range(5, len(_det)-5), 2)
else:
    pass

许多不同的列表都经历了相同的代码。有些可以长达800个运行数字,有些可以短到14个。因此,如果列表太短,代码应该返回错误并退出程序。

python python-2.7 list random
1个回答
1
投票

您可以使用random.choice选择第一个数字,从列表中删除与第一个数字不同的所有数字少于5,然后再次使用random.choice从新列表中选择第二个数字:

import random
_det = [1,3,5,6,7,4,2,5,6,7,8,4,2,1,4,9,6,4,6,9]
l = _det[5:-5]
if not l:
    raise RuntimeError('Not enough numbers in the list')
n = random.choice(l)
_list = [n]
l = [i for i in l if abs(i - n) >= 5]
if not l:
    raise RuntimeError('No number in list differs from the first number %d by more than 5' % n)
_list.append(random.choice(l))
print(_list)
© www.soinside.com 2019 - 2024. All rights reserved.