使用Python

时间:2015-11-17 05:07:44

标签: python python-2.7 tuples

我正在尝试将显示产品和成本的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)]

3 个答案:

答案 0 :(得分:8)

也许collections.Counter可以解决您的问题:

>>> from collections import Counter
>>> c = Counter(elem[1] for elem in given_list)

输出将如下所示:

Counter({1: 3, 3: 3, 2: 2, 4: 2, 5: 2, 6: 2, 7: 2, 8: 1, 9: 1})

如果你想要在问题中指定的列表中,那么你可以这样做:

>>> list(c.iteritems())
[(1, 3), (2, 2), (3, 3), (4, 2), (5, 2), (6, 2), (7, 2), (8, 1), (9, 1)]

答案 1 :(得分:2)

最快的方法是使用mysqli_map

itemgetter

答案 2 :(得分:0)

另一种方式是Defaultdict -

from collections import defaultdict

dd = defaultdict(int)

d= [('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)]
for i in d:
    dd[i[1]]+=1
counts  =  [i for i in dd.iteritems()]
print counts

打印 -

[(1, 3), (2, 2), (3, 3), (4, 2), (5, 2), (6, 2), (7, 2), (8, 1), (9, 1)]