Skip to main content
 首页 » 编程设计

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

2025年05月04日20mfrbuaa

我已经将黑白图像加载为 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]