[英]How do I check if all values in a column of a pandas dataframe are equal?
[英]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.