【问题标题】:Using string as array indices in NumPy在 NumPy 中使用字符串作为数组索引
【发布时间】:2017-11-17 13:25:40
【问题描述】:

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

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

【问题讨论】:

  • 这是否应该只处理一维数组?
  • 不,任意维度(此时最多为第五个)

标签: python arrays numpy slice


【解决方案1】:

也许因为您只期望一个非常有限的字符集,所以使用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_]

【讨论】:

  • 需要注意的是,如果 start 大于 stop,它将返回一个空数组。 arr[5:2] 为空,不会引发异常。 这就是我谈论安全性(暗示有效性)的原因。
  • 您确实意识到这是一个完全有效且有用的结果? arr[5:2] 没有引发异常是有原因的。
  • 原因是逻辑上可以理解。切片越界返回空列表。 GUI界面可能无效。
  • 你知道 f-string f'np.s_[{b}]' 不能在 Python 2.7 中使用吗?我想知道OP是如何让这个工作的!哈哈哈哈!
  • 这是“切线”。但是,我不知道您在我的声明中特别不明白什么:arr[5:2] 是空的,没有引发异常。你的问题是多余的:You do realize that this is a perfectly valid and useful result?我出去了!祝你有美好的一天!
【解决方案2】:

试试这个我认为它有效,假设你会在你的字符串中得到最小值和最大值。

import re
a = "2:4"
min = int(min(re.findall(r'(\d)',a)))
max = int(max(re.findall(r'(\d)',a)))
print arr[min:max]

【讨论】:

  • 这仅适用于用例 a,不适用于 b(与另一个数组切片)
  • 如果这两个是你唯一的输入,那么你应该有一个逻辑来识别它是数组还是切片类型。然后您可以添加 if else 条件来处理您的数据。对于数组类型,相同的代码将起作用,但只需将最大值增加一
猜你喜欢
  • 2013-09-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多