gpt4 book ai didi

python - 在 NumPy 中使用字符串作为数组索引

转载 作者:太空宇宙 更新时间:2023-11-03 14:30:15 25 4
gpt4 key购买 nike

我正在通过 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_]

关于python - 在 NumPy 中使用字符串作为数组索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47351711/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com