我想随机交换一个一维数组中的一个0和一个1,这个数组只包含0和1,很多次都是N = 10^6.这是我做一次交换的代码.

import numpy as np

# a contains only 0 and 1
a = np.array([0,1,1,0,1,1,0,0,0,1])
# j1 random position of 0, j2 random position of 1
j1 = np.random.choice(np.where(a==0)[0])
j2 = np.random.choice(np.where(a==1)[0])
# swap
a[j1], a[j2] = a[j2], a[j1]

由于我想多次执行此过程,所以在每次迭代中,我都需要使用np.where()来定位0和1的posistion,我认为这不是很有效.

Is there any other approach which can be more effecient ?

推荐答案

在执行交换时,您可以自己维护where个表达式的结果,这样就不需要重新执行那where个调用.在程序开始时,您只需执行一次,但在循环中,您需要进行增量调整.

此外,交换可以由两个赋值代替,因为您知道0将变为1,反之亦然.

a = np.array([0,1,1,0,1,1,0,0,0,1])

# One-time preprocessing

zeroes = np.where(a==0)[0]
ones = np.where(a==1)[0]
num_zeroes = len(zeroes)
num_ones = len(ones)

# In a loop:

for _ in range(100):
    # Choose random indices in zeroes/ones
    j0 = np.random.randint(num_zeroes)
    j1 = np.random.randint(num_ones)
    # Get the chosen indices for use in `a`:
    i0 = zeroes[j0]
    i1 = ones[j1]
    # Keep the two collections in sync with the swap that now happens
    zeroes[j0] = i1
    ones[j1] = i0
    # The swap itself
    a[i0] = 1
    a[i1] = 0

    # ... 

请注意,zeroesones的长度没有改变:我们可以重用每次交换时 Select 的两个插槽.

Python相关问答推荐

为什么dict(id=1,**{id:2})有时会引发KeyMessage:id而不是TypMessage?

有什么方法可以避免使用许多if陈述

将numpy数组存储在原始二进制文件中

在Polars(Python库)中将二进制转换为具有非UTF-8字符的字符串变量

Python库:可选地支持numpy类型,而不依赖于numpy

在Python argparse包中添加formatter_class MetavarTypeHelpFormatter时, - help不再工作""""

组/群集按字符串中的子字符串或子字符串中的字符串轮询数据框

给定高度约束的旋转角解析求解

如何更新pandas DataFrame上列标题的de值?

使用特定值作为引用替换数据框行上的值

如何排除prefecture_related中查询集为空的实例?

python panda ExcelWriter切换动态公式到数组公式

为什么'if x is None:pass'比'x is None'单独使用更快?

Python日志(log)模块如何在将消息发送到父日志(log)记录器之前向消息添加类实例变量

统计numpy. ndarray中的项目列表出现次数的最快方法

如何强制向量中的特定元素在Gekko中处于优化解决方案中

为用户输入的整数查找根/幂整数对的Python练习

Pandas:将值从一列移动到适当的列

用由数据帧的相应元素形成的列表的函数来替换列的行中的值

从列表中分离数据的最佳方式