python - 索引值为字符串的切片列表?

标签 python list int concatenation slice

我已经将黑白图像加载为 numpy 数组。阵列形状等于图像中的像素。我想提取特定范围的像素值,例如,

numpy_array_to_slice[160:300,28:43] 

等等,但我不想硬编码索引号。相反,我想从值列表中加载索引值。例如,我有一个索引值列表,如:

listofindexvalues = [['160:300,28:43'],['160:300,40:55'],['160:300,28:43']] 

所以我想要这样的东西:

numpy_array_to_slice[listofindexvalues[0]]

它将取代:

numpy_array_to_slice['160:300,28:43']

我已经尝试了很多没有用的东西,比如:

first,second = str(index_list[19]).replace('[','').replace(']','').replace('\'','').split(':')  ##for just one side of an index value, such as 28:59

并尝试像这样传递:

numpy_array_to_slice[int(first)+':'+int(second]

但这不起作用,因为我无法连接这些值。有什么办法可以做到这一点?

最佳答案

切片是语法,而不是字符串。查看Slicings expressions reference documentation :

The semantics for a slicing are as follows. The primary is indexed (using the same __getitem__() method as normal subscription) with a key that is constructed from the slice list, as follows. If the slice list contains at least one comma, the key is a tuple containing the conversion of the slice items; otherwise, the conversion of the lone slice item is the key. The conversion of a slice item that is an expression is that expression. The conversion of a proper slice is a slice object (see section The standard type hierarchy) whose start, stop and step attributes are the values of the expressions given as lower bound, upper bound and stride, respectively, substituting None for missing expressions.

大胆强调我的。

您可以通过直接创建 slice() 对象来绕过这种转换(从切片语法到 slice() 对象);如果需要,您可以将它们放在元组中。

所以

numpy_array_to_slice[160:300,28:43]

相当于

box = slice(160, 300), slice(28, 43)
numpy_array_to_slice[box]

我省略了 step 参数;省略时默认为 None

将此扩展到您的列表将是:

listofindexvalues = [
    (slice(160, 300), slice(28, 43)),
    (slice(160, 300), slice(40, 55)),
    (slice(160, 300), slice(28, 43))
]

for box in listofindexvalues:
    sliced_array = numpy_array_to_slice[box]

关于python - 索引值为字符串的切片列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48044222/

相关文章:

列表中 anchor 上的 CSS 背景,由于图像元素符号而无法拉伸(stretch)以覆盖整个 li

r - 根据 R 中的名称从 data.frames 列表中删除 data.frame

c++ - C++中无符号整数和无符号整数的区别

coldfusion - int()的异常行为

python - 元组作为函数参数

java聊天服务器查看在线帐户

python - 将文本添加到可以调整大小的矩形,并且无需插件即可在 Pygame 上移动

swift - 字符串转换为 Int 并将逗号替换为加号

python - arm 的 GDB 交叉编译

python - 使用不带DatetimeIndex但已知频率的statsmodels.seasonal_decompose()