【发布时间】:2015-11-17 05:07:43
【问题描述】:
我正在尝试将显示产品和成本的 Python 元组列表转换为以给定成本显示成本和产品数量的元组列表。
例如,给定以下输入:
[('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)]
我正在尝试在 Python 中创建一个可以呈现以下内容的函数。即值 1 为三种不同的产品渲染了 3 次,因此为 (1, 3)。
[(1, 3), (2, 1), (3, 2), (4, 1), (5, 2), (6, 2), (7, 2), (8, 1) (9, 1)]
【问题讨论】:
-
您只需要遍历元组并为每个值创建一个存储桶,将该存储桶中的值增加 1,这并不难。写一些代码伙伴
-
@BrijRajSingh - 这不是“pythonic”的做法。
-
@JasonEstibeiro:Brij 的解决方案是 Pythonic:使用普通的
dict很容易,但我同意该技术已被Counter取代。
标签: python python-2.7 tuples