簡體   English   中英

如何比較字典中的值

[英]How to compare values in a dictionary

如果我有這樣的字典

times = {'personA': [9,10,11,15,16,18,19],'personB': [12,14,15,16,19]}

我試圖找到這兩個人都可用的時間。 這是兩個人不可用的“阻塞”時間。 因此,9,10,11將是上午9點至11點,15,16將是下午3點至4點,依此類推。 我想找出兩個人都可以使用的1-24之間的所有數字。 是否有捷徑可尋?

使用集合而不是列表

例如

>>> times = {'personA': {9,10,11,15,16,18,19},'personB': {12,14,15,16,19}}
>>> hours = set(range(1,25))
>>> both = hours - (times['personA'] | times['personB'])
>>> both
{1, 2, 3, 4, 5, 6, 7, 8, 13, 17, 20, 21, 22, 23, 24}
times = {'personA': [9,10,11,15,16,18,19],'personB': [12,14,15,16,19]}
# Just a set with all 24 hours because
whole_day = {x for x in range(25)}

# Getting available time for both since it's what we need in fact, not busy time
free_times = {key: whole_day - set(value) for key, value in times.items()}

# Getting intersection of those free hours -> result
common_free_time = free_times['personA'] & free_times['personB']
times = {'personA': [9,10,11,15,16,18,19],'personB': [12,14,15,16,19]}
combined = times['personA'] + times['personB']
all_times = [i for i in range(1, 25)]
result = [x for x in all_times if x not in combined]

我將創建一組所有可用時間,並刪除其中一個人不可用的所有插槽:

available = set(range(12,25))
for v in times.values():
    available = available - set(v)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM