4

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?

CDJB
  • 14,043
  • 5
  • 29
  • 55
  • 1
    Tuples are immutable. You just have to iterate, count and make new tuples and append them to a new list – tst Dec 12 '19 at 12:05

1 Answers1

4

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)]
CDJB
  • 14,043
  • 5
  • 29
  • 55