检查字典中的多个值对
有没有办法让这段代码变得更简短呢?
我想要在字典中检查一下,如果 a, b
,a-foo, b-foo
或者 a-bar, b-bar
其中任何一个存在,就打印一些东西。这里的 -foo
和 -bar
是固定的值。
有没有一种简洁的方法,可以用一个 if 语句来检查这些呢?
这个字典看起来是这样的:
defaultdict(<class 'set'>, {'key1': {'elem1', 'elem2'}})
if "a" in my_dic["key1"] and "b" in my_dic["key1"]:
print("Exists")
if "a-foo" in my_dic["key1"] and "b-foo" in my_dic["key1"]:
print("Exists")
if "a-bar" in my_dic["key1"] and "b-bar" in my_dic["key1"]:
print("Exists")
2 个回答
1
像这样吗?
if (
("a" in my_dic["key1"] and "b" in my_dic["key1"])
or ("a-foo" in my_dic["key1"] and "b-foo" in my_dic["key1"])
or ("a-bar" in my_dic["key1"] and "b-bar" in my_dic["key1"])
):
print("Exists")
还有一般情况下:
subsets: list[set[str]] = [{"a", "b"}, {"a-foo", "b-foo"}, {"a-bar", "b-bar"}]
if any(subset.issubset(my_dic["key1"]) for subset in subsets):
print("Exists")
5
这个方法可以很好地扩展到N个条目。
valuepairs = (("a", "b"), ("a-foo", "b-foo"), ("a-bar", "b-bar"))
if any(all(key in my_dic["key1"] for key in pair) for pair in valuepairs):
print("Exists")
你也可以像这样懒惰地生成值对:
roots = ("a", "b")
extensions = ("", "-foo", "-bar")
valuepairs = ((root + extension for root in roots) for extension in extensions)