I'm looking for a way to get all items from a python list that are between 2 items. The algorithm must warp through the whole array.
For instance:
I have a string like "Mo-Fr"
and I want to end up with a list:
[Monday, Tuesday, Wednesday, Thursday, Friday]
but I want it to also work this way:
string = "Fr-Mo"
list = Friday, Saturday, Sunday, Monday
my code looks at the moment like this:
string = 'Mo-Fr'
days_order = ['Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa', 'So']
days_dict = {'Mo' : 'Montag',
'Di' : 'Dienstag',
'Mi' : 'Mittwoch',
'Do' : 'Donnerstag',
'Fr' : 'Freitag',
'Sa' : 'Samstag',
'So' : 'Sonntag',}
days = string.split('-')
days = [days_order.index(day) for day in days]
days_list = [days_dict[day] for day in days_order if days_order.index(day) in range(days[0], days[1] + 1)]
So my code works fine if the string looks like "Mo-Fr" but of course doesn't work with "Fr-Mo". Any ideas how to get this working in a clean way?
Thanks!
A simple solution is to double the days_order
list so that it contains all rotations of the weekdays:
>>> days_order = ['Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa', 'So'] * 2
then get the start/end indexes like this:
>>> string = 'Fr-Mo'
>>> days = string.split('-')
>>> start = days_order.index(days[0])
>>> end = days_order.index(days[1], start + 1) + 1
and finally build the list of days like this:
>>> [days_dict[day] for day in days_order[start:end]]
['Freitag', 'Samstag', 'Sonntag', 'Montag']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With