Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x Python根据条件获取类列表的索引_Python 3.x_Sorting - Fatal编程技术网

Python 3.x Python根据条件获取类列表的索引

Python 3.x Python根据条件获取类列表的索引,python-3.x,sorting,Python 3.x,Sorting,我有以下代码: import numpy as np np.random.seed(1) class Order: def __init__(self, amount, orderId): self.orderId = orderId self.amount = amount n = 5 amounts = np.random.randint(low=8, high=20, size=n) orderIds = np.arange(n

我有以下代码:

import numpy as np
np.random.seed(1)
class Order:
    def __init__(self, amount, orderId):
        self.orderId = orderId
        self.amount = amount 
        

n = 5
amounts = np.random.randint(low=8, high=20, size=n)
orderIds = np.arange(n)

orders = [Order(amounts[i],orderIds[i]) for i in range(n)]
当排序列表的累计金额超过某个阈值时,我想得到所有orderId的orderId列表

例如:

orderIds = [0, 1, 2, 3, 4]
amounts = [15, 18, 19, 16, 10]
descending_ordered_amounts = [19, 18, 16, 15, 10]
cumsum = [19, 37, 52, 68, 78]
threshold = 55
cumsum > threshold # [False, False, False, True, True]
然后我想得到id=[0,4]


请问,最快的方法是什么?

这里的主要问题是按照值对ID进行排序,以便知道返回什么。 可以这样做,使用中间值来保存数量和ID的元组

orderIds = [0, 1, 2, 3, 4]
amounts = [15, 18, 19, 16, 10]

des = [(x, y) for x, y in zip(amounts, orderIds)]
des.sort(key=lambda x: x[0], reverse=True)

sortedIds = np.array([x[1] for x in des])
threshold = 55
ids = np.cumsum([x[0] for x in des]) > threshold

print(sortedIds[ids])
这将打印满足要求的ID。我没有使用降序的变量,因为它存储在des的第一列,所以我只是在cumsum中使用了一个列表理解