Python 是否可以在不使用递归的情况下生成排除一组数字的随机数?

2023-11-08Python开发问题
3

本文介绍了Python 是否可以在不使用递归的情况下生成排除一组数字的随机数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我查看了 Python Docs(我可能误解了),但我没有看到有在不调用递归函数的情况下执行此操作的方法(如下所示).
我想做的是生成一个随机值,其中不包括中间值.

I looked over Python Docs (I may have misunderstood), but I didn't see that there was a way to do this (look below) without calling a recursive function.
What I'd like to do is generate a random value which excludes values in the middle.

换句话说,
假设我希望 X 是一个不在其中的随机数
范围(a - b, a + b)
我可以在第一次通过时这样做吗,

1.我是否必须不断生成一个数字,
2. 检查是否在range(),
3.洗涮涮涮?

In other words,
Let's imagine I wanted X to be a random number that's not in
range(a - b, a + b)
Can I do this on the first pass,
or
1. Do I have to constantly generate a number,
2. Check if in range(),
3. Wash rinse ?

至于我为什么不想写递归函数,
1.感觉"我不应该这样做
2. 我这样做的一组数字实际上最终可能会非常大,并且
...我听说堆栈溢出很糟糕,我可能只是在这样做时过于谨慎.

As for why I don't wish to write a recursive function,
1. it 'feels like' I should not have to
2. the set of numbers I'm doing this for could actually end up being quite large, and
... I hear stack overflows are bad, and I might just be being overly cautious in doing this.

我确信有一种很好的、Pythonic、非递归的方式来做这件事.

I'm sure that there's a nice, Pythonic, non-recursive way to do it.

推荐答案

使用random.choice().在此示例中,a 是您的下限,b 和 c 之间的范围被跳过,d 是您的上限.

Use random.choice(). In this example, a is your lower bound, the range between b and c is skipped and d is your upper bound.

import random
numbers = range(a,b) + range(c,d)
r = random.choice(numbers)

这篇关于Python 是否可以在不使用递归的情况下生成排除一组数字的随机数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

在xarray中按单个维度的多个坐标分组
groupby multiple coords along a single dimension in xarray(在xarray中按单个维度的多个坐标分组)...
2024-08-22 Python开发问题
15

Pandas中的GROUP BY AND SUM不丢失列
Group by and Sum in Pandas without losing columns(Pandas中的GROUP BY AND SUM不丢失列)...
2024-08-22 Python开发问题
17

GROUP BY+新列+基于条件的前一行抓取值
Group by + New Column + Grab value former row based on conditionals(GROUP BY+新列+基于条件的前一行抓取值)...
2024-08-22 Python开发问题
18

PANDA中的Groupby算法和插值算法
Groupby and interpolate in Pandas(PANDA中的Groupby算法和插值算法)...
2024-08-22 Python开发问题
11

PANAS-基于列对行进行分组,并将NaN替换为非空值
Pandas - Group Rows based on a column and replace NaN with non-null values(PANAS-基于列对行进行分组,并将NaN替换为非空值)...
2024-08-22 Python开发问题
10

按10分钟间隔对 pandas 数据帧进行分组
Grouping pandas DataFrame by 10 minute intervals(按10分钟间隔对 pandas 数据帧进行分组)...
2024-08-22 Python开发问题
11