简体   繁体   English

numpy 数组中的“翻转”值?

[英]“flip” values in numpy array?

I have a list of numbers within a range of 1.. n I want to 'flip' some of the numbers, but it shouldnt repeat any of the existing numbers.我有一个 1 范围内的数字列表。我想“翻转”一些数字,但它不应该重复任何现有数字。

I imagine it this way:我是这样想象的:

  1. pick numbers to flip选择要翻转的数字
  2. flip them but check that they dont repeat翻转它们,但检查它们是否重复

Here is step 1:这是第1步:

  lst = np.array([5,9,88,55,90,43])
 In [95]: z = np.random.choice(lst, 2,replace=False)
 Out[95]: array([ 9, 43])

    ixs = np.where(lst == z)[0]
    #does not guarantee that the new numbers are not already in lst!
    lst[ixs] = np.random.choice(xrange(0,n),2,replace=False)

now how do i make sure that the new random numbers dont repeat without doing checks in a loop.现在我如何确保新的随机数在不循环检查的情况下不会重复。

Any other numpy way?还有其他 numpy 方式吗?


Flip mean change from one value to another.翻转意味着从一个值变为另一个值。 You can think of the list of numbers as indexes to a bitarray, where the number specifies if the bit is 1.您可以将数字列表视为位数组的索引,其中数字指定位是否为 1。

So flipping means for every flip of 1 => 0, flip another bit from 0 => 1所以翻转意味着每次翻转 1 => 0,从 0 => 1 翻转另一位

in: np.array([5,9,88,55,90,43]) out: np.array([5,9,46,55,21,43])输入:np.array([5,9,88,55,90,43]) 输出:np.array([5,9,46,55,21,43])

two number was changed两个数字被改变了

You can use sets.您可以使用集合。

s = set(xrange(0, n))

lst[ixs] = np.random.choice(s.difference(lst), 2, replace=False)

It's arguable if it's much more efficient, but it is certainly cleaner.如果它更有效,这是有争议的,但它肯定更清洁。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM