Porting random permutation code from MATLAB to Pyt

2020-07-18 03:39发布

How can this MATLAB code be translated to Python?

For example with random files:

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条回答
做个烂人
2楼-- · 2020-07-18 04:05
from random import shuffle

def randperm(n):
    lst = [i for i in range(1, n+1)]
    shuffle(lst)
    return lst
查看更多
Bombasti
3楼-- · 2020-07-18 04:25
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]
查看更多
欢心
4楼-- · 2020-07-18 04:31

if you don't want to depend of numpy and you are not dealing with large arrays/performance is not an issue, try this:

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
查看更多
登录 后发表回答