python - 从值为对象列表的字典中查找最小值

标签 python dictionary

我有一个服务类类型的 Python 对象列表。还有另一个字典 grps,其中对象根据数据成员分组。同一组中的对象对其分组所依据的数据成员具有完全相同的值。

from collections import defaultdict
class service:
    def __init__(self, tasknum, candidatenum, features, cost):
        self.tasknum = tasknum
        self.candidatenum = candidatenum
        self.features = features
        self.cost = cost

s11 = service(1,1, features = [1], cost = 30)
s12 = service(1,2, features = [1], cost = 50)
s13 = service(1,3, features = [1], cost = 70)
s14 = service(1,4, features = [1], cost = 200)
s15 = service(1,5, features = [2], cost = 20)

lst = []
lst.append(s11)
lst.append(s12)
lst.append(s13)
lst.append(s14)
lst.append(s15)

grps = defaultdict(list)
for x in lst:
    grps[tuple(x.features)].append(x)

上面有两组,一组对应features = [1],一组对应features = [2]

defaultdict(<class 'list'>, {(1,): [<__main__.service object at 0x7efe19a2d6d8>, <__main__.service object at 0x7efe19a2d4e0>, <__main__.service object at 0x7efe1d7e9550>, <__main__.service object at 0x7efe1d7e9588>], (2,): [<__main__.service object at 0x7efe1d7e95c0>]})

对于每个这样的组,我想返回一个具有最小成本值的服务对象,也就是说,在上面,第一组将返回 s11 服务,第二组将返回 s15 服务,因为它是组中唯一的对象。

有没有更好的方法可以不使用字典来做到这一点,比如只使用列表就可以做到这一点?

最佳答案

在列表理解中,您可以对组的每个成员调用 min() 并使用获取 cost 属性的键。 operator.attrgetter这很方便:

from operator import attrgetter
# array of min-cost services
mins = [min(g, key = attrgetter('cost')) for g in grps.values()]

# just the costs
[c.cost for c in mins] # [30, 20]

关于python - 从值为对象列表的字典中查找最小值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55980277/

相关文章:

python - 在此 return 语句中使用 and 运算符

python - 只用键制作字典?

python - 访问嵌套字典 panda 中的单元格的最佳方式是什么?

python - 选择字典键 :values randomly

python - 使 OrderedDict 中的重复值唯一

python - 是否有将数据帧的某些值写入 Python 中的 .txt 文件的函数?

python - 区间类 - Python

python - 如何使用 remote_addr header 限制对 POST api 的访问?

python - 如何测试字典是否包含某些键

python - 分段最小二乘的动态规划算法