繁体   English   中英

查找列表中对象最少出现的Python方法

[英]Pythonic way to find fewest occurrences of object in list

我有2条相关的字典, itemsbookings清单。 我需要确定预订最少的商品。

真正的示例在数据库中,但是为了便于练习,请考虑以下数据:

from datetime import datetime

item1 = {'foo1'}
item2 = {'foo2'}
items = [item1, item2]

booking1 = {'Start':datetime(2012,1,1), 'Item':'foo1'}
booking2 = {'Start':datetime(2012,1,2), 'Item':'foo1'}
booking3 = {'Start':datetime(2012,1,1), 'Item':'foo2'}
bookings = [booking1, booking2, booking3]

如何有效确定预订量最少的商品? 任何帮助将不胜感激!

from collections import Counter

# create the counter, from most common to least common. reverse it, and get the first item.
item, num = Counter(b['Item'] for b in bookings).most_common()[::-1][0]

效率更高(由senderle提供):

from collections import Counter

c = Counter(b['Item'] for b in bookings)
item = min(c, key=c.get)

您可以使用collections.Counter (Python的多集)轻松地(尽管不是特别有效)来执行此操作:

import collections
c = collections.Counter()

for booking in bookings:
    c[booking['Item']] += 1

c.most_common()[:-2:-1]
[('foo2', 1)]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM