【问题标题】:Use built-in setattr simultaneously with index slicing同时使用内置的 setattr 和索引切片
【发布时间】:2015-01-11 20:09:20
【问题描述】:

我正在编写的一个类需要使用存储 numpy 数组的变量名属性。我想为这些数组的切片分配值。我一直在使用 setattr,以便我可以让属性名称有所不同。我为切片赋值的尝试如下:

class Dummy(object):
        def __init__(self, varname):
        setattr(self, varname, np.zeros(5))

d = Dummy('x')
### The following two lines are incorrect
setattr(d, 'x[0:3]', [8,8,8])
setattr(d, 'x'[0:3], [8,8,8])

上述 setattr 的使用都不会产生我想要的行为,即 d.x 是一个包含条目 [8,8,8,0,0] 的 5 元素 numpy 数组。可以用 setattr 做到这一点吗?

【问题讨论】:

    标签: python numpy slice setattr


    【解决方案1】:

    想想你通常会如何编写这段代码:

    d.x[0:3] = [8, 8, 8]
    # an index operation is really a function call on the given object
    # eg. the following has the same effect as the above
    d.x.__setitem__(slice(0, 3, None), [8, 8, 8])
    

    因此,要进行索引操作,您需要获取名称x 引用的对象,然后对其执行索引操作。例如。

    getattr(d, 'x')[0:3] = [8, 8, 8]
    

    【讨论】:

    • 很好的解决方案@Dunes,很有启发性。谢谢!
    猜你喜欢
    • 2014-08-18
    • 2023-01-10
    • 2021-07-18
    • 2018-10-17
    • 2014-05-07
    • 2014-12-24
    • 1970-01-01
    • 1970-01-01
    • 2018-12-29
    相关资源
    最近更新 更多