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

时间:2012-03-07 02:05:18

标签: python list

我有两个相关的词典列表,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]

如何有效确定哪个项目的预订量最少?任何帮助将不胜感激!

2 个答案:

答案 0 :(得分:4)

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]

效率更高(由sentle提供):

from collections import Counter

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

答案 1 :(得分:1)

使用collections.Counter(Python的多重集),您可以轻松地完成此任务,但不是特别有效:

import collections
c = collections.Counter()

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

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