-1
get_quantities({'t1': ['Vegetarian stew', 'Poutine', 'Vegetarian stew'], 't3': ['Steak pie', 'Poutine', 'Vegetarian stew'], 't4': ['Steak pie', 'Steak pie']})

这是我的字典。t指表。

我需要返回一个新字典:

{'Vegetarian stew': 3, 'Poutine': 2, 'Steak pie': 3} like this.

我该如何编写这段代码?

4

1 回答 1

0
from collections import Counter

def get_quantities(tables):
    counter = Counter()
    for table in tables.iterValues():
        counter.update(table)
    return counter

这将返回一个Counter,它是一个类似字典的对象。

例如,

quantities = get_quantities({'t1': ['Vegetarian stew', 'Poutine', 'Vegetarian stew'], 't3': ['Steak pie', 'Poutine', 'Vegetarian stew'], 't4': ['Steak pie', 'Steak pie']})
print quantities['Vegetarian stew']

将打印3

于 2013-10-27T22:58:26.397 回答