Python:从2个已知项之间的列表中获取项 [英] Python: get items from list between 2 known items

查看:59
本文介绍了Python:从2个已知项之间的列表中获取项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种从python列表中获取介于2个项目之间的所有项目的方法.该算法必须扭曲整个数组.

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.

例如:

我有一个像"Mo-Fr"这样的字符串 我想列出一个清单:

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

因此,如果字符串看起来像"Mo-Fr",那么我的代码可以正常工作,但"Fr-Mo"当然不起作用. 有什么想法可以使它干净地工作吗?

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?

谢谢!

推荐答案

一个简单的解决方案是将days_order列表加倍,使其包含工作日的所有轮换:

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

这篇关于Python:从2个已知项之间的列表中获取项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆