使用 Python 计算元组的出现次数 [英] Count occurrence of tuples with Python
问题描述
我正在尝试将显示产品和成本的 Python 元组列表转换为显示给定成本下的成本和产品数量的元组列表.
例如,给定以下输入:
[('Product1', 9), ('Product2', 1),('产品3', 1), ('产品4', 2),('Product5', 3), ('Product6', 4),('Product7', 5), ('Product8', 6),('Product9', 7), ('Product10', 8),('Product11', 3), ('Product12', 1),('Product13', 2), ('Product14', 3),('Product15', 4), ('Product16', 5),('Product17', 6), ('Product18', 7)]
我正在尝试在 Python 中创建一个函数来呈现以下内容.即对于三种不同的产品,值 1 被渲染了 3 次,因此是 (1, 3).
[(1, 3), (2, 1), (3, 2), (4, 1), (5, 2), (6, 2), (7, 2), (8, 1) (9, 1)]
也许 collections.Counter
可以解决您的问题:
输出将如下所示:
计数器({1: 3, 3: 3, 2: 2, 4: 2, 5: 2, 6: 2, 7: 2, 8: 1, 9: 1})
如果您希望将其放在问题中指定的列表中,那么您可以这样做:
<预><代码>>>>列表(c.iteritems())[(1, 3), (2, 2), (3, 3), (4, 2), (5, 2), (6, 2), (7, 2), (8, 1), (9, 1)]I'm trying to convert a list of Python tuples that display product and cost to a list of tuples that display the cost and the count of products at a given cost.
For example, given the below input:
[('Product1', 9), ('Product2', 1),
('Product3', 1), ('Product4', 2),
('Product5', 3), ('Product6', 4),
('Product7', 5), ('Product8', 6),
('Product9', 7), ('Product10', 8),
('Product11', 3), ('Product12', 1),
('Product13', 2), ('Product14', 3),
('Product15', 4), ('Product16', 5),
('Product17', 6), ('Product18', 7)]
I'm trying to create a function in Python that would render the below. i.e. The value 1 is rendered 3 times for three different products, hence (1, 3).
[(1, 3), (2, 1), (3, 2), (4, 1), (5, 2), (6, 2), (7, 2), (8, 1) (9, 1)]
Maybe collections.Counter
could solve your problem:
>>> from collections import Counter
>>> c = Counter(elem[1] for elem in given_list)
Output will look like this:
Counter({1: 3, 3: 3, 2: 2, 4: 2, 5: 2, 6: 2, 7: 2, 8: 1, 9: 1})
If you want it in a list like you've specified in the question, then you can do this:
>>> list(c.iteritems())
[(1, 3), (2, 2), (3, 3), (4, 2), (5, 2), (6, 2), (7, 2), (8, 1), (9, 1)]
这篇关于使用 Python 计算元组的出现次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!