繁体   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