首页 > 解决方案 > 创建一个随机数列表并过滤列表以仅包含大于 50 的数字

问题描述

我正在使用列表理解来创建一个带有 numpy 的随机数列表。有没有办法检查生成的随机数是否大于 50,然后才将其附加到列表中。

我知道我可以简单地使用:

numbers = [np.random.randint(50,100) for x in range(100)]

这将解决问题,但我只想知道是否有可能以某种方式检查 np.random.randint(1,100) 生成的数字是否大于 50

就像是

numbers = [np.random.randint(1,100) for x in range(100) if {statement}]

因为比较 np.random.randit 会生成另一个与第一个不同的数字。

我只想知道是否有可能在将生成的数字添加到列表之前对其进行过滤。

标签: pythonnumpyrandom

解决方案


您使用 numpy,因此我们可以利用索引方法。

my_array = np.random.randint(1, 100, size=100)
mask = my_array > 50
print(my_array[mask]) # Contain only value greater than 50

但是,当然,做你想做的最好的方法就是这样。

results = np.random.randint(51,100, size=100)
# If you really need a list
results_list = results.tolist()

请不要循环遍历一个 numpy 数组。

编辑:根据@norok2 评论将 my_list 替换为 my_array 。

Edit2:速度考虑

麻木的

带口罩

%%timeit
my_array = np.random.randint(1, 100, size=100)
mask = my_array > 50
my_array[mask]

每个循环 5.31 µs ± 127 ns(平均值 ± 标准偏差。7 次运行,每次 100000 次循环)

10,000,000 个元素:

1 个循环,最好的 3 个:每个循环 198 毫秒

使用 numpy where (@Severin Pappadeux anwser)

%%timeit
q = np.random.randint(1, 100, 1000)
m = np.where(q > 50)
q[m]

每个循环 20.9 µs ± 663 ns(平均值 ± 标准偏差。7 次运行,每次 10000 次循环)

10,000,000 个元素:

1 个循环,最好的 3 个:每个循环 196 毫秒

纯蟒蛇

@Alexander Cécile 回答的一部分

%%timeit
rand_nums = (random.randint(0, 99) for _ in range(10))
arr = [val for val in rand_nums if val > 50]

每个循环 19.4 µs ± 1.99 µs(7 次运行的平均值 ± 标准偏差,每次 10000 个循环)

10,000,000 个元素:

1 个循环,最好的 3 个:每个循环 11.4 秒

混合numpy和list

@DrBwts 回答

%%timeit
number = [x for x in np.random.randint(1, high=100, size=100) if x > 50]

每个循环 28.9 µs ± 1.52 µs(7 次运行的平均值 ± 标准偏差,每次 10000 个循环)

10,000,000 个元素:

1 个循环,最好的 3 个:每个循环 2.76 秒

@makis 回答

%%timeit 
numbers = [x for x in (np.random.randint(1,100) for iter in range(100)) if x > 50]

每个循环 164 µs ± 19.4 µs(7 次运行的平均值 ± 标准偏差,每次 10000 个循环)

10,000,000 个元素:

1 个循环,最好的 3 个:每个循环 12.2 秒

@Romero情人节答案

rand = filter(lambda x: x>50, np.random.randint(1,100,100))
rand_list = list(rand)

每个循环 35.9 µs ± 1.97 µs(7 次运行的平均值 ± 标准偏差,每次 10000 次循环)

10,000,000 个元素:

1 个循环,最好的 3 个:每个循环 3.41 秒

结论

  • 在简单的任务上,这些方法都很好。
  • 在大型阵列上,numpy 粉碎了竞争。

提供更多信息的答案

  • @norok2
  • @亚历山大·塞西尔

推荐阅读