交换 numpy 数组中的两个值. [英] Swap two values in a numpy array.

查看:39
本文介绍了交换 numpy 数组中的两个值.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有比以下代码更有效的方法来交换 numpy 一维数组的两个值?

Is there something more efficient than the following code to swap two values of a numpy 1D array?

input_seq = arange(64)

ix1 = randint(len(input_seq))
ixs2 = randint(len(input_seq))

temp = input_seq[ix2]
input_seq[ix2] = input_seq[ix1] 
input_seq[ix1] = temp

推荐答案

您可以使用元组解包.元组解包允许您避免在代码中使用临时变量(实际上我相信 Python 代码本身在幕后使用了临时变量,但它的级别要低得多,因此速度要快得多).

You can use tuple unpacking. Tuple unpacking allows you to avoid the use of a temporary variable in your code (in actual fact I believe the Python code itself uses a temp variable behind the scenes but it's at a much lower level and so is much faster).

input_seq[ix1], input_seq[ix2] = input_seq[ix2], input_seq[ix1]

我已将此问题标记为重复,答案在 dupe post 有更多细节.

I have flagged this question as a duplicate, the answer in the dupe post has a lot more detail.

这篇关于交换 numpy 数组中的两个值.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆