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

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

问题描述

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

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代码本身在幕后使用了temp变量,但它的级别低得多,因此速度要快得多).

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]

我已将此问题标记为重复,即

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

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

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