简体   繁体   English

元组作为多维数组中的索引以及切片

[英]tuple as index in multidimensional array together with slicing

I have a 3-dimensional array A , and I need to access A[:,1,1] through the tuple x=[1,1] .我有一个 3 维数组A ,我需要通过元组x=[1,1]访问A[:,1,1] ] 。 Something like this:像这样的东西:

x = [1,1]
A[:,*x]

However, doing that I get a syntax error.但是,这样做会出现语法错误。 I would love to be able to access the elements of A[:,1,1] using the variable x , how can I do that?我希望能够使用变量x访问A[:,1,1]的元素,我该怎么做?

Thank you!谢谢!


Second question:第二个问题:

How to do the same but instead of slicing : do it with a boolean array.如何做同样的事情,而不是切片:使用 boolean 数组。 For example if t is an array of booleans, obtain A[t, *x]例如,如果t是一个布尔数组,则获得A[t, *x]

You can do the following:您可以执行以下操作:

import numpy as np

A = np.arange(12).reshape((2, 3, 2))
print(A)

x = [1, 1]
print(A[(slice(None), *x)])

You can use slice(None) instead of : to build a tuple of slices.您可以使用slice(None)而不是:来构建切片元组。 The tuple environment allows for value unpacking with the * operator. tuple 环境允许使用 * 运算符进行值解包。

Output: Output:

[[[ 0  1]
  [ 2  3]
  [ 4  5]]

 [[ 6  7]
  [ 8  9]
  [10 11]]]

[3 9]

To verify it matches:要验证它是否匹配:

import numpy as np

A = np.arange(12).reshape((2, 3, 2))
x = [1, 1]
s = (slice(None), *x)
print(np.allclose(A[s], A[:, 1, 1]))  # True

*This is a modification of answers found here: Slicing a numpy array along a dynamically specified axis *这是对此处找到的答案的修改:沿动态指定的轴切片 numpy 数组


Edit to reflect edit on question and comment:编辑以反映对问题和评论的编辑:

To clarify, you can unpack any iterable you like in the tuple environment.澄清一下,您可以在元组环境中解压缩任何您喜欢的可迭代对象。 The * operator functions normally in within the tuple. * 运算符通常在元组中起作用。 Order your elements however you like.随心所欲地订购您的元素。 Mix in different iterables, types, slice(None) , how ever you want to build your slices, as long as you end up with a valid sequence of values, it will behave as expected.混合不同的迭代、类型、 slice(None) ,无论你想如何构建你的切片,只要你最终得到一个有效的值序列,它就会按预期运行。

import numpy as np

A = np.arange(12).reshape((2, 3, 2))
t = [True, False]
x = [1, 1]
print(np.allclose(A[(*t, *x)], A[True, False, 1, 1]))  # True

You can also add full lists as well in the tuple:您还可以在元组中添加完整列表:

print(np.allclose(A[(t, *x)], A[[True, False], 1, 1]))  # True

you can use slice(None) instead of : , So你可以使用slice(None)而不是: ,所以

y = tuple([slice[None]] + x)
A[y]

is what you need.是你需要的。

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

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