簡體   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