如何解决如何获得给定索引的排列?
| 我有一个对象列表:array = [object0,object1,object2,object3,object4]
我想更改给定排列的项目的顺序:
permutation = [ 2,4,1,3 ]
python中是否有一条命令可以执行以下操作:
result = Permute(array,permutation)
result = [object2,object4,object0,object3]
我知道我可以用一个简单的for
循环来做...
解决方法
如果我们假设
permutation
是0-n
的适当置换(每个正好出现一次),那么以下代码应该工作:
result=[array[i] for i in permutation]
, 在Python中,使用列表理解很容易做到:
result = [array[i] for i in permutation]
, 为了完整起见,完全没有版本:
seed = [\'foo\',\'bar\',\'baz\']
permutation = [1,2,0]
result = map(lambda i: seed[i],permutation)
print result # --> [\'bar\',\'baz\',\'foo\']
不过,我宁愿选择名单理解专家。 ;)
, 使用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]
参考:
https://docs.scipy.org/doc/numpy-1.15.0/reference/generation/numpy.random.shuffle.html
, 您可以使用索引交换。
你有两个数组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
所以,做测试
d = np.array(range(0,15))
r = np.array(range(16,31))
display(d,r)
>>> array([ 0,1,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,14]),>>> array([16,30]))
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。