随机化两个列表(numpy in)并在 python 中保持顺序 [英] randomizing two lists(numpy in) and maintaining order in python
问题描述
我有两个 2d numpy 列表.我想洗牌,但只是外侧洗牌.
I have two 2d numpy lists. I want to shuffle it, but just outer side shuffle.
如果我随机排列订单列表 a,我希望列表 b 遵循列表 a 的顺序.
If i randomize order list a, I want list b to follow list a's order.
我已经看到 随机化两个列表并在 python 中保持顺序 但这对我来说似乎不起作用.
I have seen randomizing two lists and maintaining order in python but this looks not work for me.
下面的代码是我现在所做的.
The below code is how I'm doing now.
但是对于大的 numpy 列表来说太慢了.
But it's too slow for big numpy lists.
import numpy as np
import random
a = np.array([[1,2,3], [4,5,6], [7,8,9], [10,11,12]])
b = np.array([[100,200,300,400,500], [600,700,800,900,901], [101,102,103,104,105], [501,502,503,504,505]])
r = [i for i in range(4)]
random.shuffle(r)
newa = np.empty((0, 3))
newb = np.empty((0, 5))
for rr in r:
newa = np.append(newa, [a[rr]], axis=0)
newb = np.append(newb, [b[rr]], axis=0)
print(newa)
print(newb)
有没有pythonic或更快的方法来做到这一点?
Any pythonic or faster way to do this?
感谢回答.
推荐答案
您的想法是正确的,但是附加到数组非常耗时,因为它每次都会重新分配整个缓冲区.相反,您可以只使用混洗后的索引:
You have the right idea, but appending to an array is very time consuming, since it reallocates the entire buffer every time. Instead, you can just use the shuffled index:
a = np.array([[1,2,3], [4,5,6], [7,8,9], [10,11,12]])
b = np.array([[100,200,300,400,500], [600,700,800,900,901], [101,102,103,104,105], [501,502,503,504,505]])
r = np.arange(4)
np.random.shuffle(r)
newa = a[r]
newb = b[r]
这篇关于随机化两个列表(numpy in)并在 python 中保持顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!