我正在通过 GUI 处理 python 中的大型数值数组。
我想将切片功能公开给 GUI 中的文本框,这样我就可以轻松选择用于手头计算的数组部分。
我想做的简单例子:
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]
我发现了切片函数,但我需要手动解析字符串并创建切片。有没有更简单的方法?
也许因为您只期望非常有限的字符集,所以使用是可以接受的eval
这一次:
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_]
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)