Python 交换 numpy 数组中的两个值。

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22847410/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 01:48:37  来源:igfitidea点击:

Swap two values in a numpy array.

pythonnumpyscipyswap

提问by Gioelelm

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

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

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

采纳答案by Ffisegydd

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).

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

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 posthas a lot more detail.

我已将此问题标记为重复,dupe 帖子中的答案有更多详细信息。

回答by Lewistrick

I see you're using numpy arrays. In that case, you can also do this:

我看到你在使用 numpy 数组。在这种情况下,您也可以这样做:

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