[英]How to change the index of an element in a list/array to another position/index without deleting/changing the original element and its value
[英]Shuffle array such that the expected index of an element will be its original index
考慮一個數組:
a=[0,1,2,3,4,5,6,...99]
我想對其進行改組,以便每個元素最終都出現在它開始的 position 中; 即 0 預計將出現在 position 0 中,1 預計將出現在 position 1 中,2 預計將出現在 position 2 中。
我也希望能夠將它用於一般數組。
編輯:
我已經取得了一些進展,並且我認為由於問題引起了一些混亂,人們可能會發現這更容易。
a = ['a','b','c']
b = list(range(0,len(a)))
c = np.random.normal(0,1,len(a))
d = b+c
np.sort(d)
最后一行返回按 d 排序的 d。 我想得到按d
排序的a
的元素。 即,我想在此排序中將 map 應用於 d 應用於a
。
我想你在numpy.argsort
之后。 一個接近你所擁有的實現將是這樣的:
import numpy as np
def nearsort(arr, *, amount=1):
rv = np.random.normal(np.arange(len(arr)), amount)
result = []
for i in np.argsort(rv):
result.append(arr[i])
return result
amount
參數確定項目可以移動的距離,較小的值使大的重新排列不太可能。 作為一個簡單的例子,我們從以下位置返回['b', 'a', 'c']
:
np.random.seed(3)
nearsort(['a', 'b', 'c'])
請注意,項目可以任意移動,因此您可能希望使用不同的分布來獲得更多控制權。 例如,可以使用均勻分布(通過randint
),或者可以使用具有由p
指定的權重的choice
來進行更多控制。 例如:
def unisort(arr, *, pchange=0.1):
weights = [pchange / 2, 1 - pchange, pchange / 2]
rv = np.random.choice([-1.1, 0, 1.1], size=len(arr), p=weights)
ii = np.argsort(np.arange(len(arr)) + rv)
return [arr[i] for i in ii]
將確保項目不會移動太遠。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.