Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum values inside a list of tuples and order by weekday [duplicate]

I have a list of tuples holding ('Day of Week', n) as follows:

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

I want to produce the following output, a list of tuples holding ('Day of Week', sum_n), where sum_n is the sum of all the corresponding n values in my initial list. Note that the elements should be in order of weekday.

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

How can this be achieved?

like image 520
sankar nataraj Avatar asked Oct 29 '25 17:10

sankar nataraj


1 Answers

With a list comprehension:

>>> 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)]

To sort with second element descending:

>>> 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)]

To sort by day of week (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)]
like image 50
CDJB Avatar answered Oct 31 '25 11:10

CDJB



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!