【问题标题】:Surprising behavior of numpy.random.shuffle [duplicate]numpy.random.shuffle 的令人惊讶的行为 [重复]
【发布时间】:2019-08-06 16:54:30
【问题描述】:

在我自己的函数中使用 numpy.random.shuffle 时,它​​意外更改了我的全局变量。不知道是不是对它的使用有什么误解。

numpy 版本是'1.16.4'

import numpy as np
def shuffle_test(a):
    np.random.shuffle(a)
    b=a
    return b

outer_input  = np.array(range(10))
print(outer_input)

outer_output = shuffle(outer_input)
print(outer_input)

这是结果 洗牌前的输入:

[0 1 2 3 4 5 6 7 8 9]

洗牌后输入:

[5 4 7 1 8 2 6 0 9 3]

【问题讨论】:

标签: python numpy


【解决方案1】:

这不是偶然的;这是np.random.shuffle的描述行为

通过打乱其内容就地修改序列

你可以这样做:

import numpy as np

outer_input  = np.array(range(10))
np.random.shuffle(outer_input)
outer_input

# array([1, 9, 7, 4, 3, 6, 0, 5, 2, 8])   # for instance

【讨论】:

    猜你喜欢
    • 2019-10-05
    • 1970-01-01
    • 2014-02-16
    • 2021-09-28
    • 2021-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-27
    相关资源
    最近更新 更多