验证字典中互斥元素

1 投票
3 回答
783 浏览
提问于 2025-04-16 20:47

我有一个字典,这个字典里可以有三个键:urllinkpath。在我验证这个字典的时候,这三个键不能同时存在。也就是说,如果字典里有url这个键,那么pathlink就不能有,反之亦然。

还有一个问题是:主要的键不能是空的(不能是null或者空字符串'')。

我经常遇到这样的情况,所以写了很多条件语句来检查这些情况。有没有更好的方法呢?

谢谢。

3 个回答

-1

也许你不应该使用字典,而是应该用元组:

(value, "url") or (value, "path") or (value, "link")
1

我赞同CatPlusPlus的观点,不过他代码里有个问题,我已经在下面评论过了,这里是修复的方法:

if (url in d and d[url] not in [None, '']) ^ (link in d and d[link] not in [None, '']) ^ (path in d and d[path] not in [None, '']):
    # mutex condition satisfied
else:
    # at least two are keys in the dict or none are
4

要测试你的条件,你可以这样做:

# d is your dict
has_url  = bool(d.get('url',  False))
has_link = bool(d.get('link', False))
has_path = bool(d.get('path', False))
# ^ is XOR
if not (has_url ^ has_link ^ has_path):
    # either none of them are present, or there is more than one, or the
    # one present is empty or None

为了找出哪个条件成立,并根据它来执行操作,你可能还是需要三个不同的分支。

撰写回答