元组列表中的总和值

时间:2019-12-12 12:02:53

标签: python python-3.x list tuples

我有一个包含('Day of Week', n)的元组列表,如下所示:

[('Wed', 1), ('Wed', 1), ('Thu', 1), ('Thu', 0), ('Tue', 0), ('Mon', 0), ('Sun', 0), ('Sat', 0), 
 ('Fri', 0)]

我想产生以下输出,一个包含('Day of Week', sum_n)的元组列表,其中sum_n是初始列表中所有对应的n值的总和。

 [('Wed', 2), ('Thu', 1), ('Tue', 0), ('Mon', 0), ('Sun', 0), ('Sat', 0), ('Fri', 0)]

如何实现?

1 个答案:

答案 0 :(得分:4)

具有列表理解:

>>> l = [('Wed', 1), ('Wed', 1), ('Thu', 1), ('Thu', 0), ('Tue', 0), ('Mon', 0), ('Sun', 0), ('Sat', 0), ('Fri', 0)]
>>> [(x, sum(y[1] for y in l if y[0] == x)) for x in set(z[0] for z in l)]
[('Sun', 0),
 ('Tue', 0),
 ('Mon', 0),
 ('Wed', 2),
 ('Sat', 0),
 ('Thu', 1),
 ('Fri', 0)]

要以第二个元素降序排序:

>>> res = [(x, sum(y[1] for y in l if y[0] == x)) for x in set(z[0] for z in l)]
>>> sorted(res, key=lambda x: x[1], reverse=True)
[('Wed', 2),
 ('Thu', 1),
 ('Sun', 0),
 ('Tue', 0),
 ('Mon', 0),
 ('Sat', 0),
 ('Fri', 0)]

要按星期几(more answers here)进行排序:

>>> sorted_days = ["Fri", "Sat", "Sun", "Mon", "Tue", "Wed", "Thu"]
>>> sorted(res, key=lambda x: sorted_days.index(x[0]))
[('Fri', 0),
 ('Sat', 0),
 ('Sun', 0),
 ('Mon', 0),
 ('Tue', 0),
 ('Wed', 2),
 ('Thu', 1)]