繁体   English   中英

Python 是否可以将两个 if 和一个 else 语句放在一起?

[英]Python is it possible to put two if and one else statements together?

if 'a' in dict:
    dict['a'] do something
if 'b' in dict:
    dict['b'] do something
# After checking the above two if statements, run the else statement below
else:
    dict do something

我想检查dict中是'a'还是'b' 如果我使用elif语句,那么如果'a'dict中,则检查'b'将被跳过。

是否可以检查上述两种情况,如果'a''b'都不在dict中,那么我们还要做其他else吗?

我可以以一种乏味的方式实现它。

if `'a' or 'b'` in dict:
    if 'a' in dict:
        dict['a'] do something
    if 'b' in dict:
        dict['b'] do something
else:
    dict do something
dictionary = {"a":1, "b":2}
if (cond1 := "a" in dictionary) | (cond2 := "b" in dictionary):
    if cond1:
        pass
    if cond2:
        pass
else:
    pass

使用语言中最近添加的 - :=运算符,您可以捕获这两个条件的值。 虽然您仍然需要分别检查它们是真还是假,但它可以让您跳过重复相同的检查两次。

| 必须使用后者来代替or由于后者的惰性评估 - 如果 cond1 为 True,则永远不会检查第二个条件并且 cond2 将未定义。 | 将确保检查这两个条件,但它使解决方案不像应有的那样漂亮。

这是一个想法 - 首先检查是否不存在任何相关键; 如果那是False ,则对确实存在的每个相关键执行相关操作。

如果你有另一个字典来保存每个key: action (这意味着你的do something应该成为正确的函数)。

就像是:

# Put your logic for each key here
def do_something_no_keys(): 
    print('No keys found!')

def do_something_a(): 
    print('Key "a" found!')

def do_something_b(): 
    print('Key "b" found!')

# Associate each possible key with their logic here
action_dict = {
    'a': do_something_a,
    'b': do_something_b,
}

# These are the values that you want to check
value_dict = {
    'a': 'foo',
    'c': 'bar',
}

if all(key not in value_dict for key in action_dict):
    do_something_no_keys()
else:
    for key, action in action_dict.items():
        if key in value_dict:
            action()

当前 output 是Key "a" found! ,但是如果您修改value_dict中的键,则可以看到此更改。

没有办法让if s 只检查 a 或 b 之一,但是然后以某种方式让else同时考虑 a 和 b。 如果你想有一个单独的代码分支,一个单独的 b,一个用于组合(或其否定),你需要三个 if 以某种方式或其他方式。 您带有嵌套 ifs 的“乏味”示例是一个完全合理的解决方案。

很难从这个问题中确切地说出您认为什么是令人满意的替代方案,但这里有一个:

if 'a' in d:
    do_something(d['a'])
if 'b' in d:
    do_something(d['b'])
if 'a' not in d and 'b' not in d:
    do_something_else()

如果仅检查前两个条件的析取的否定,则通过制作第三个来避免额外的嵌套级别。 不过,这并不比您的“乏味”解决方案更好。

neither_a_nor_b = True

if 'a' in dict:
    neither_a_nor_b = False
    # suite 1

if 'b' in dict:
    neither_a_nor_b = False
    # suite 2

if neither_a_nor_b:
    # suite 3

如果套件 1 和 2 相同,则可以使用循环:

neither_a_nor_b = True

for x in ['a', 'b']:
    if x in dict:
        neither_a_nor_b = False
        # suite 1/2

if neither_a_nor_b:
    # suite 3

尽管在任何一种情况下,您都可以简单地将neither_a_nor_b替换为像all(x not in dict for x in ['a', 'b'])这样的显式(如果冗余)测试。

您可以堆叠 if 语句并使用 elif 语句:

dictionary = {"a": 1, "b": 2}
    if "a" in dictionary:
        print("a")
    if "b" in dictionary:
        print("b")
    elif "a" not in dictionary and "b" not in dictionary:
        print("Neither")

印刷:

a
b

尽管

dictionary = {"z": 1, "x": 2}
    if "a" in dictionary:
        print("a")
    if "b" in dictionary:
        print("b")
    elif "a" not in dictionary and "b" not in dictionary:
        print("Neither")

印刷:

Neither

减少检查,使用其他答案的想法:

if first := "a" in dictionary:
    print("a")
if "b" in dictionary:
    print("b")
elif not first:
    print("Neither")

如果您使用for循环遍历 dict,则可以使用continue语句,如下所示:

for el in dict:
  if 'a' in el:
      do something
      continue
  if 'b' in el:
      do something
      continue
  else:
      do something

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM