使用 python 打乱数组,使用 python 随机化数组项顺序

发布于 2024-07-11 17:55:37 字数 30 浏览 7 评论 0原文

用 python 打乱数组的最简单方法是什么?

What's the easiest way to shuffle an array with python?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(11

脱离于你 2024-07-18 17:55:37
import random
random.shuffle(array)
import random
random.shuffle(array)
兮子 2024-07-18 17:55:37
import random
random.shuffle(array)
import random
random.shuffle(array)
眸中客 2024-07-18 17:55:37

使用 sklearn

from sklearn.utils import shuffle
X=[1,2,3]
y = ['one', 'two', 'three']
X, y = shuffle(X, y, random_state=0)
print(X)
print(y)

输出:

[2, 1, 3]
['two', 'one', 'three']

优点:您可以同时随机化多个阵列,而不会破坏映射。 “random_state”可以控制可重现行为的洗牌。

Alternative way to do this using sklearn

from sklearn.utils import shuffle
X=[1,2,3]
y = ['one', 'two', 'three']
X, y = shuffle(X, y, random_state=0)
print(X)
print(y)

Output:

[2, 1, 3]
['two', 'one', 'three']

Advantage: You can random multiple arrays simultaneously without disrupting the mapping. And 'random_state' can control the shuffling for reproducible behavior.

許願樹丅啲祈禱 2024-07-18 17:55:37

如果您想要一个新数组,可以使用sample

import random
new_array = random.sample( array, len(array) )

Just in case you want a new array you can use sample:

import random
new_array = random.sample( array, len(array) )
霊感 2024-07-18 17:55:37

其他答案是最简单的,但是有点烦人的是 random.shuffle 方法实际上并不返回任何内容 - 它只是对给定列表进行排序。 如果您想链接调用或只是能够在一行中声明一个打乱的数组,您可以执行以下操作:

import random
def my_shuffle(array):
    random.shuffle(array)
    return array

然后您可以执行以下操作:

for suit in my_shuffle(['hearts', 'spades', 'clubs', 'diamonds']):

The other answers are the easiest, however it's a bit annoying that the random.shuffle method doesn't actually return anything - it just sorts the given list. If you want to chain calls or just be able to declare a shuffled array in one line you can do:

import random
def my_shuffle(array):
    random.shuffle(array)
    return array

Then you can do lines like:

for suit in my_shuffle(['hearts', 'spades', 'clubs', 'diamonds']):
预谋 2024-07-18 17:55:37

处理常规 Python 列表时,random.shuffle() 将完成前面答案所示的工作。

但当谈到 ndarray(numpy.array) 时,random.shuffle 似乎破坏了原来的 ndarray。 这是一个例子:

import random
import numpy as np
import numpy.random

a = np.array([1,2,3,4,5,6])
a.shape = (3,2)
print a
random.shuffle(a) # a will definitely be destroyed
print a

只需使用:np.random.shuffle(a)

random.shuffle一样,np.random.shuffle对数组进行洗牌到位。

When dealing with regular Python lists, random.shuffle() will do the job just as the previous answers show.

But when it come to ndarray(numpy.array), random.shuffle seems to break the original ndarray. Here is an example:

import random
import numpy as np
import numpy.random

a = np.array([1,2,3,4,5,6])
a.shape = (3,2)
print a
random.shuffle(a) # a will definitely be destroyed
print a

Just use: np.random.shuffle(a)

Like random.shuffle, np.random.shuffle shuffles the array in-place.

无人问我粥可暖 2024-07-18 17:55:37

您可以使用随机键对数组进行排序,

sorted(array, key = lambda x: random.random())

键只能读取一次,因此在排序过程中比较项目仍然有效。

但看起来 random.shuffle(array) 会更快,因为它是用 C 编写的,

这是 O(Nlog(N)) 顺便说一句

You can sort your array with random key

sorted(array, key = lambda x: random.random())

key only be read once so comparing item during sort still efficient.

but look like random.shuffle(array) will be faster since it written in C

this is O(Nlog(N)) btw

誰ツ都不明白 2024-07-18 17:55:37

除了前面的回复之外,我还想介绍一下另一个功能。

numpy.random.shuffle 以及 random.shuffle 执行就地洗牌。 但是,如果你想返回一个打乱的数组,numpy.random.permutation 就是要使用的函数。

In addition to the previous replies, I would like to introduce another function.

numpy.random.shuffle as well as random.shuffle perform in-place shuffling. However, if you want to return a shuffled array numpy.random.permutation is the function to use.

野心澎湃 2024-07-18 17:55:37

我不知道我使用了 random.shuffle() 但它返回“None”给我,所以我写了这个,可能对某人有帮助

def shuffle(arr):
    for n in range(len(arr) - 1):
        rnd = random.randint(0, (len(arr) - 1))
        val1 = arr[rnd]
        val2 = arr[rnd - 1]

        arr[rnd - 1] = val1
        arr[rnd] = val2

    return arr

I don't know I used random.shuffle() but it return 'None' to me, so I wrote this, might helpful to someone

def shuffle(arr):
    for n in range(len(arr) - 1):
        rnd = random.randint(0, (len(arr) - 1))
        val1 = arr[rnd]
        val2 = arr[rnd - 1]

        arr[rnd - 1] = val1
        arr[rnd] = val2

    return arr
时光与爱终年不遇 2024-07-18 17:55:37

请注意,random.shuffle() 不应用于多维数组,因为它会导致重复。

想象一下,您想要沿数组的第一个维度对数组进行打乱,我们可以创建以下测试示例,

import numpy as np
x = np.zeros((10, 2, 3))

for i in range(10):
   x[i, ...] = i*np.ones((2,3))

以便沿第一个轴,第 i 个元素对应于一个 2x3 矩阵,其中所有元素都等于 i。

如果我们对多维数组使用正确的洗牌函数,即np.random.shuffle(x),数组将根据需要沿第一个轴洗牌。 但是,使用 random.shuffle(x) 会导致重复。 您可以通过在洗牌后运行 len(np.unique(x)) 来检查这一点,这会给您 10 (如预期)与 np.random.shuffle() 但仅大约5 使用random.shuffle()时。

Be aware that random.shuffle() should not be used on multi-dimensional arrays as it causes repetitions.

Imagine you want to shuffle an array along its first dimension, we can create the following test example,

import numpy as np
x = np.zeros((10, 2, 3))

for i in range(10):
   x[i, ...] = i*np.ones((2,3))

so that along the first axis, the i-th element corresponds to a 2x3 matrix where all the elements are equal to i.

If we use the correct shuffle function for multi-dimensional arrays, i.e. np.random.shuffle(x), the array will be shuffled along the first axis as desired. However, using random.shuffle(x) will cause repetitions. You can check this by running len(np.unique(x)) after shuffling which gives you 10 (as expected) with np.random.shuffle() but only around 5 when using random.shuffle().

酷炫老祖宗 2024-07-18 17:55:37
# arr = numpy array to shuffle

def shuffle(arr):
    a = numpy.arange(len(arr))
    b = numpy.empty(1)
    for i in range(len(arr)):
        sel = numpy.random.random_integers(0, high=len(a)-1, size=1)
        b = numpy.append(b, a[sel])
        a = numpy.delete(a, sel)
    b = b[1:].astype(int)
    return arr[b]
# arr = numpy array to shuffle

def shuffle(arr):
    a = numpy.arange(len(arr))
    b = numpy.empty(1)
    for i in range(len(arr)):
        sel = numpy.random.random_integers(0, high=len(a)-1, size=1)
        b = numpy.append(b, a[sel])
        a = numpy.delete(a, sel)
    b = b[1:].astype(int)
    return arr[b]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文