Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: get items from list between 2 known items

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!

like image 439
Sonic Avatar asked Oct 08 '15 14:10

Sonic


1 Answers

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']
like image 153
ekhumoro Avatar answered Sep 23 '22 15:09

ekhumoro