【问题标题】:Random pick 2 numbers with a minimum difference of 5随机选择 2 个最小差为 5 的数字
【发布时间】:2018-09-11 06:47:43
【问题描述】:

我有一个运行号码列表,我试图在列表中随机选择 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 个。因此,如果列表太短,代码应该返回错误并退出程序。

【问题讨论】:

  • 如果差值小于 5 两次,您的代码将不会做正确的事情。您可能想要使用递归函数调用。

标签: python python-2.7 list random


【解决方案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)

【讨论】:

    猜你喜欢
    • 2014-07-06
    • 2010-12-18
    • 1970-01-01
    • 1970-01-01
    • 2011-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-02
    相关资源
    最近更新 更多