编写“或”语句的有效方法

时间:2018-10-06 10:01:47

标签: python python-3.x

在标准输入中,我输入了两个单词,如果它们出现在字典中,我想对其进行处理。这意味着我可以使两个单词中的一个或两个都不匹配(在这种情况下,我将用错误消息包装代码)。这与布尔或门非常相似。我可以这样写我的脚本:

if word1 in dict and word2 in dict:
    # process word1
    # process word2
elif word1 in dict:
    # process word1
elif word2 in dict:
    # process word2
else:
    # error msg

但是,这似乎很多余。是否有一个简单的替代方法?我有一个单独的函数,可以一次处理这些单词之一。

3 个答案:

答案 0 :(得分:1)

如果处理word1和word2彼此独立,则可以如下修改代码:

word_found = False
if word1 in dict:
    #process word1
    word_found = True
if word2 in dict:
    #process word2
    word_found = True
if not word_found:
    #error message

答案 1 :(得分:1)

现在很明显,两个单词的处理都没什么特别的,也就是说,仅是单个单词的顺序处理,您可以通过将错误检查上移到顶部来减少代码:

if word1 not in dict and word2 not in dict:
    # raise Exception or print and return
if word1 in dict:
    # process word1
if word2 in dict:
    # process word2

可读,不需要额外的状态变量。

答案 2 :(得分:0)

您可以leverage all(..)检查词典中是否有多个键-这将测试所有事物,直到找到一个False或全部为True:

def doSmthWithAllOfThem(words,dictionary):
    print(words, "are in it")
    print(sum(dictionary[word] for word in words) )

d = {"w{}".format(i):i for i in range(10)}

words = {"w1","w9","w4"} 

if all(w in d for w in words):
    doSmthWithAllOfThem(words,d)
elif "w9" in dict:
    pass
else:
    raise ValueError("not in")

输出:

{'w4', 'w9', 'w1'} are in it
14

您也可以use set-intersection operation

words = {"w1","w9","w4"} 

if words & set(d.keys()) == words:
    doSmthWithAllOfThem(words,d)

或(对@jpp表示祝贺)use set-issubset operation

if words <= set(d.keys()):
    doSmthWithAllOfThem(words,d)

(两种set-usage情况下的输出都与上述情况相同)


相交仅返回两个集合中的东西-如果之后的结果与words相等,则所有元素都在您的字典中。