使用排序来对一组对象进行排序

2024-05-20 08:36:49 发布

您现在位置:Python中文网/ 问答频道 /正文

使用这样的for循环:

for k in time :
        def byPrice(stock):
            st = stock.get_momentum
            return st[k]
        s = sorted(obj, key=byPrice)

我想对stock对象列表按每个stock对象中动量数组中的第k项进行排序

class stock:
    def __init__(self, name, price):
        self.name = name
        self.lens = len(price)

    def get_momentum(self):
        momentum = []
        for i in np.arange(lens):
             count = close[i]/close[i-60]
             momentum.append(count)
        return momentum

但是我收到一条警告说'method' object is not subscriptable。错误在st[k]


Tags: 对象nameinselfforgetreturndef
2条回答

只需添加括号:

for k in time :
        def byPrice(stock):
            st = stock.get_momentum()
            return st[k]
        s = sorted(obj, key=byPrice)

你需要实际调用你的方法。否则,st是方法对象,st[k]没有意义

您也可以在不使用定义byPrice的情况下执行此操作

s = sorted(obj, key=lambda stock:stock.get_momentum()[k]) 

(不过,可以说更难阅读)。或者可以在循环外定义byPrice,并让它将k作为另一个参数

您正在将变量st设置为实际的类方法stock.get_momentum,而方法/函数对象没有基于索引的访问权限。这就是not subscriptable的意思

只是一个小错误,经常发生!将st = stock.get_momentum更改为st = stock.get_momentum()

相关问题 更多 >