Reputation: 13
I have a list of integers [1, 2...40, 41...]
that represent months of a few years. i.e. 1
is January of year 1, 13
is January of year 2, and so on. When trying to convert into just the month integer (all Januarys to 1
, etc.) I'm using month_int % 12
but it turns December into 0
. I wrote the following small block to catch the Decembers but was wondering if there's a more efficient way?
for month_int in month_list:
if not(bool(month_int % 12)):
# Dec exception here
else:
# work as normal
Basically, I want to change lists like this:
[1, 2...12, 13, 14, 15...]
[1, 2...12, 1, 2, 3...]
Upvotes: 1
Views: 92
Reputation: 73450
fodma1's answer has you covered, but you can do it even shorter:
month = month % 12 or 12
>>> l = [1, 2, 12, 13, 14, 15]
>>> [m % 12 or 12 for m in l]
[1, 2, 12, 1, 2, 3]
Upvotes: 1
Reputation: 39
Since there are more months that aren't December it would be slightly more efficient to have that condition first e.g.
for month_int in month_list:
if (bool(month_int % 12)):
# normal
else:
# December
Since it will only move to the else once every 12 iterations then.
Upvotes: 0
Reputation: 3535
You are indexing from 1 instead of zero. What you can do is subtract 1 and then add 1 to the remainder again:
month = (month - 1) % 12 + 1
Upvotes: 3