在NumPy中使用字符串作为数组索引 [英] Using string as array indices in NumPy

查看:99
本文介绍了在NumPy中使用字符串作为数组索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在通过GUI在python中处理大型数值数组. 我想将切片功能公开给GUI中的文本框,因此我可以轻松选择应用于手算的一部分数组.

I'm handling large numerical arrays in python through a GUI. I'd like to expose the slicing capabilities to a textbox in a GUI, so I can easily choose part of the array that should be used for the calculation at hand.

我想做的简单例子:

arr = array([0, 10, 20, 30, 40, 50, 60, 70, 80, 90])

a = "2:4" # example string from GUI Textbox
b = "[3, 4, 5]" # example string from GUI Textbox


print arr[a] # not valid code -> what should be written here to make it work?
print arr[b] # not valid code -> what should be written here to make it work?

应输出:

[20, 30]
[30, 40, 50]

我了解了slice函数,但是我需要手动解析我的字符串并创建一个slice.有没有更简单的方法?

I found out about the slice function, but I'd need to parse my string manually and create a slice. Is there a simpler way?

推荐答案

也许由于您只希望使用非常有限的字符集,因此可以一次使用eval来接受它:

Maybe since you are only expecting a very limited character set it is acceptable using eval this once:

if not all(c in "1234567890-[],: " for c in b): # maybe also limit the length of b?
    # tell user you couldn't parse and exit this branch
slice_ = eval(f'np.s_[{b}]')
# slice_ can now be applied to your array: arr[slice_]

这篇关于在NumPy中使用字符串作为数组索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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