python - 如何在没有两个连续元素重复的情况下洗牌数字数组?

标签 python arrays numpy random

我目前正在尝试获取一组像这样随机打乱的数字:

label_array = np.repeat(np.arange(6), 12)

唯一的限制是洗牌的连续元素不能是相同的数字。为此,我目前正在使用此代码:

# Check if there are any occurrences of two consecutive 
# elements being of the same category (same number)
num_occurrences = np.sum(np.diff(label_array) == 0)

# While there are any occurrences of this...
while num_occurrences != 0:
    # ...shuffle the array...
    np.random.shuffle(label_array)

    # ...create a flag for occurrences...
    flag = np.hstack(([False], np.diff(label_array) == 0))
    flag_array = label_array[flag]

    # ...and shuffle them.
    np.random.shuffle(flag_array)

    # Then re-assign them to the original array...
    label_array[flag] = flag_array

    # ...and check the number of occurrences again.
    num_occurrences = np.sum(np.diff(label_array) == 0)

虽然这适用于这种大小的数组,但我不知道它是否适用于更大的数组。即使这样,也可能需要很多时间。

那么,有更好的方法吗?

最佳答案

在技术上可能不是最佳答案,但愿它能满足您的要求。

import numpy as np
def generate_random_array(block_length, block_count):
    for blocks in range(0, block_count):
        nums = np.arange(block_length)
        np.random.shuffle(nums)
        try:
            if nums[0] == randoms_array [-1]:
                nums[0], nums[-1] = nums[-1], nums[0]
        except NameError:
            randoms_array = []
        randoms_array.extend(nums)
    return randoms_array


generate_random_array(block_length=1000, block_count=1000)

关于python - 如何在没有两个连续元素重复的情况下洗牌数字数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52539338/

相关文章:

ios - NSArray 元素无法匹配 Swift 数组元素类型 - 带有 Swift 库的 Objective-C(图表)

python - 如何在 python 中随机洗牌数据和目标?

python - Pandas .at 抛出 ValueError : At based indexing on an integer index can only have integer indexers

Python:根据子列表以不同方式对列表中列表中的列表元素进行切片

python - 无法使用 jsonpickle 将 json 字符串解码为 python 对象

java - 为什么我会收到 '.class' 预期错误?简单数组脚本

c - 有没有办法 malloc 一个数组大小为 10 的整数指针并返回它的值?

python - numpy中有没有一种方法可以测试矩阵是否是单一的

python - 沿 axis=1 对值进行排序,NaN 位于行开头

python - 如何使用未终止的多行注释处理标记化错误(python 2.6)