You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何简洁高效生成有序且相邻差≤10的唯一随机整数列表

简洁实现方案

首先要明确一个前提:因为要求任意两元素差值不超过10,且所有元素唯一,所以n的取值必须≤11(从x到x+10共有11个不同整数,超过这个数量无法满足条件)。

最简洁的实现方式

利用random.sample直接从连续11个整数的区间中抽取n个唯一值,再排序即可,代码非常紧凑:

import random

def generate_target_list(n):
    if n > 11:
        raise ValueError("n cannot exceed 11 — you can't have more than 11 unique integers where all pairwise differences are ≤10")
    base = random.randint(0, 1000)  # 可根据需求调整随机数的起始范围
    return sorted(random.sample(range(base, base + 11), n))

代码说明

  • random.sample:从指定序列中随机抽取n个不重复的元素,天然保证了元素的唯一性。
  • range(base, base + 11):生成连续11个整数,区间跨度恰好为10,因此任意两个元素的差值必然≤10。
  • sorted():对抽取的元素进行排序,满足最终列表的有序要求。

一行式简化(忽略边界检查的话)

如果能确保调用时n≤11,还可以写成更短的一行:

import random
generate_list = lambda n: sorted(random.sample(range(random.randint(0,1000), random.randint(0,1000)+11), n))

不过不推荐忽略边界检查,实际使用时加上参数校验更稳妥。

内容的提问来源于stack exchange,提问作者Dylan Boyd

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 01:12:04