簡體   English   中英

如何獲得索引的排列?

[英]How can i get a permutation given indexes?

我有一個對象列表:

array = [object0,object1,object2,object3,object4]

我想改變給定排列的項目的順序:

permutation = [ 2 , 4 , 0 , 1 , 3 ]

在python中是否有一個命令可以執行以下操作:

result = Permute(array,permutation)

result = [object2,object4,object0,object1,object3]

我知道我可以通過一個簡單的for循環來做到這一點....

在Python中,使用列表理解很容易做到:

result = [array[i] for i in permutation]

如果我們假設permutation0-n的正確排列(每個只出現一次),則以下代碼應該起作用:

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/generated/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,  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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM