繁体   English   中英

如何检查列表/元组中的某些值是否相等?

[英]How do I check if some values in list/tuple is equal?

我正在尝试打印一个摊位的营业时间。 我正在尝试检查所有营业时间值是否相同,我应该打印

Monday to Sunday: 0800 - 2200

否则它应该分成不同的工作时间。

Monday to Friday: 0800 - 2200
Saturday to Sunday: 1100 - 2000

列表的值是根据档位创建的。 例如,其中一个摊位有这样的营业时间。

operating_hours_list = [['MONDAY', '0800 - 2200'], ['TUESDAY', '0800 - 2200'], ['WEDNESDAY', '0800 - 2200'], ['THURSDAY', '0800 - 2200'], ['FRIDAY', '0800 - 2200'], ['SATURDAY', '1100 - 2000'], ['SUNDAY', '1100 - 2000']]

谢谢!

您可以使用itertools.groupby()按具有相同小时数的连续元素(嵌套列表的索引1 )对列表进行分组:

import itertools

operating_hours_list = [['MONDAY', '0800 - 2200'], ['TUESDAY', '0800 - 2200'], ['WEDNESDAY', '0800 - 2200'], ['THURSDAY', '0800 - 2200'], ['FRIDAY', '0800 - 2200'], ['SATURDAY', '1100 - 2000'], ['SUNDAY', '1100 - 2000']]
groups = itertools.groupby(operating_hours_list, lambda x: x[1])
# groups looks like
# [('0800 - 2200', <itertools._grouper object at 0x1174c8470>), ('1100 - 2000', <itertools._grouper object at 0x1176f3fd0>)]
# where each <itertools._grouper> object contains elements in the original list
for hours, days in groups:
    day_list = list(days)
    # if there's only one unique day with these hours, then just print that day
    # e.g. day_list = [['MONDAY', '0800 - 2200']], so we need to take the first element of the first element
    # we additionally call .title() on it to turn it to 'Title Case' instead of all-caps
    if len(day_list) == 1:
        print("{}: {}".format(day_list[0][0].title(), hours))
    # otherwise, we get both the first day with these hours (index 0), 
    # and the last day with these hours (index -1).
    else:
        print("{} to {}: {}".format(day_list[0][0].title(), day_list[-1][0].title(), hours))

这输出:

Monday to Friday: 0800 - 2200
Saturday to Sunday: 1100 - 2000

既然你正在寻找指导,我会帮你一些伪代码(因为给你答案对学习没有帮助)

首先,您需要一些东西来存储一组开放时间。 这可以是一组或多组,每组将有一个日期和时间范围。 因此,二维列表是一种选择:

openings = [[]]

我们知道我们可以从星期一及其时间和 go 开始,直到我们找到具有不同时间的一天或到达周末。 所以我们可以这样开始:

openings = [[operating_hours_list[0][0], operating_hours_list[0][1]]

这将让我们开始

[['Monday', '0800 - 2200']]

现在从第二天开始循环,直到找到不同的时间(这现在是伪代码 - 尝试翻译成 Python)

for d from 1 to 6: #Tuesday to Sunday indices
    if operating_hours_list[d][1] == openings[end][1]:
        keep going
    else: # found a day with a different time
        append (' to ' + operating_hours_list[d-1][0]) to openings[end][0]
        append a new opening set to openings with day and times from opening_hours_list

现在这会让你开始,然后想想当你到周末时你将如何处理。 请记住,您可以使用[-1]索引列表中的最后一项,并分步执行并运行和测试,以便在出现问题时解决问题。 希望这会有所帮助,并且您可以从这个问题中学到一些东西!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM