将随机置换代码从MATLAB移植到Python

问题描述 投票:4回答:3

如何将此MATLAB代码转换为Python?

例如,使用随机文件:

FileA = rand([10,2]);
FileB = randperm(10);

for i=1:10
fileC(FileB(i),1)=FileA(i,1); %for the x
fileC(FileB(i),2)=FileA(i,2); %for the y
end
python matlab
3个回答
7
投票
import numpy as np
array_a = np.random.rand(10,2)
array_b = np.random.permutation(range(10))

array_c = np.empty(array_a.shape, array_a.dtype)
for i in range(10):
    array_c[array_b[i], 0] = array_a[i, 0]
    array_c[array_b[i], 1] = array_a[i, 1]

1
投票

如果您不想依赖numpy并且不处理大型数组/性能不是问题,请尝试以下操作:

import random
def randperm(a):
    if(not a):
        return a
     b = []
     while(a.__len__()):
         r = random.choice(a)
         b.append(r)
         a.remove(r)

     return b

0
投票
from random import shuffle

def randperm(n):
    lst = [i for i in range(1, n+1)]
    shuffle(lst)
    return lst
© www.soinside.com 2019 - 2024. All rights reserved.