[英]How can i get a permutation given indexes?
I've got a list of objects: 我有一个对象列表:
array = [object0,object1,object2,object3,object4]
and i want to change the order of the items given a permutation: 我想改变给定排列的项目的顺序:
permutation = [ 2 , 4 , 0 , 1 , 3 ]
Is there a command in python that will do something like: 在python中是否有一个命令可以执行以下操作:
result = Permute(array,permutation)
result = [object2,object4,object0,object1,object3]
I know i can do it with a simple for
loop.... 我知道我可以通过一个简单的for
循环来做到这一点....
在Python中,使用列表理解很容易做到:
result = [array[i] for i in permutation]
如果我们假设permutation
是0-n
的正确排列(每个只出现一次),则以下代码应该起作用:
result=[array[i] for i in permutation]
Just for the sake of completeness a version with no for at all: 只是为了完整性,没有在所有版本的缘故:
seed = ['foo', 'bar', 'baz']
permutation = [1, 2, 0]
result = map(lambda i: seed[i], permutation)
print result # --> ['bar', 'baz', 'foo']
I'd rather stick with the list comprehension guys, though. 不过,我宁愿坚持列表理解人员。 ;) ;)
Use shuffle method from numpy 从numpy使用shuffle方法
import numpy as np
arr = np.arange(10)
np.random.shuffle(arr)
print(arr)
[1 7 5 2 9 4 3 6 0 8] [1 7 5 2 9 4 3 6 0 8]
Reference: https://docs.scipy.org/doc/numpy-1.15.0/reference/generated/numpy.random.shuffle.html 参考: https : //docs.scipy.org/doc/numpy-1.15.0/reference/generated/numpy.random.shuffle.html
You can use index swapping. 您可以使用索引交换。 You a have two array a and b 你有两个阵列a和b
def swap_random(a, b):
"""Randomly swap entries in two arrays."""
# Indices to swap
swap_inds = np.random.random(size=len(a)) < 0.5 # your threshold
# Make copies of arrays a and b for output
a_out = np.copy(a)
b_out = np.copy(b)
# Swap values
a_out[swap_inds] = b[swap_inds]
b_out[swap_inds] = a[swap_inds]
return a_out, b_out
So, do the test 所以,做测试
d = np.array(range(0,15))
r = np.array(range(16,31))
display(d,r)
>>> array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14])
>>> array([16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30])
display(swap_random(d, r))
>>> (array([ 0, 17, 2, 3, 20, 21, 22, 7, 24, 25, 10, 11, 28, 13, 14]),
>>> array([16, 1, 18, 19, 4, 5, 6, 23, 8, 9, 26, 27, 12, 29, 30]))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.