如何生成具有彼此不同的随机值的 numpy 数组

Mad*_*x17 6 arrays random numpy

我刚刚开始学习 Python 库,今天我陷入了 numpy 练习中。

假设我想生成一个 5x5 的随机数组,其值彼此不同。此外,其值必须介于 0 到 100 之间。

我已经在这里查看过,但没有找到适合我的问题的解决方案。在向您求助之前,请参阅我咨询过的帖子:

这是我解决这个练习的尝试:

import numpy as np

M = np.random.randint(1, 101, size=25)
for x in M:
    for y in M:
        if x in M == y in M:
            M = np.random.randint(1, 101, size=25)
            print(M)
Run Code Online (Sandbox Code Playgroud)

通过这样做,我得到的只是一个值错误:ValueError:具有多个元素的数组的真值不明确。使用 a.any() 或 a.all()

因此,我的第二次尝试如下:

M = np.random.randint(1, 101, size=25)
a = M[x]
b = M[y]

for a.any in M:
    for b.any in M:
        if a.any in M == b.any in M:
            M = np.random.randint(1, 101, size=25)
            print(M)
Run Code Online (Sandbox Code Playgroud)

我再次收到错误:AttributeError: 'numpy.int64' object attribute 'any' is read-only。

你能让我知道我做错了什么吗?我花了几天时间思考这个问题,但没有想到其他:(

太感谢了!

dan*_*444 5

不确定这是否可以满足您的所有需求,但它适用于您的示例:

np.random.choice(np.arange(100, dtype=np.int32), size=(5, 5), replace=False)
Run Code Online (Sandbox Code Playgroud)

  • “没有替代的选择”实际上就是他想要的。 (2认同)