【发布时间】:2019-03-03 12:10:32
【问题描述】:
我目前正在尝试获取一组随机随机排列的数字:
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)
虽然这适用于这种大小的数组,但我不知道它是否适用于更大的数组。即便如此,也可能需要很长时间。
那么,有没有更好的方法呢?
【问题讨论】:
-
有趣的问题。您肯定已经注意到,这对每个阵列都是不可能的。一种可能的方法是一次选择一个元素,但将其限制为设置元素,如果选择它们不会导致错误的解决方案......但是我不确定这是否易于计算。
-
顺便说一句,您的阵列是否始终遵循相同的结构?也就是说,它是否总是有
n不同的元素,每个元素都重复k次?还是重复次数没有规定?
标签: python arrays numpy random