我有一个连续的数字列表,我试图在列表中随机选择 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 个。因此,如果列表太短,代码应该返回错误并退出程序。
最佳答案
您可以使用random.choice
选择第一个数字,从列表中删除与第一个数字相差小于5的所有数字,然后使用random.choice
code> 再次从新列表中选择第二个数字:
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)
关于python - 随机抽取 2 个数字,相差最小为 5,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52270179/