【问题标题】:How to append a list in Python based on condition?如何根据条件在 Python 中附加列表?
【发布时间】:2022-01-27 01:18:18
【问题描述】:

我在附加列表时遇到问题。以下是代码:

score_Resp = 0
score_O2Sat = 5
score_SBP = 0
score_HR = 1
score_Temp = 0

Abnormal = []
if score_Resp != 0:
    Abnormal.append("Resp")
elif score_O2Sat != 0:
    Abnormal.append("O2Sat")
elif score_SBP != 0:
    Abnormal.append("SBP")
elif score_HR != 0:
    Abnormal.append("HR")
elif score_Temp != 0:
    Abnormal.append("Temp")
else:
    print("Invalid Statement!")
print("Abnormal Vitals:", Abnormal)

输出:

Abnormal Vitals: ['O2Sat']

什么时候应该:

Abnormal Vitals: ['O2Sat', 'HR']

有人可以帮我解决问题吗?而且,有人可以用更少的代码改进代码吗?谢谢

【问题讨论】:

    标签: python list append


    【解决方案1】:

    您不应该使用elif。只需简单的 ifs 即可评估每个条件。

    像这样:

    if score_Resp != 0:
        Abnormal.append("Resp")
    if score_O2Sat != 0:
        Abnormal.append("O2Sat")
    if score_SBP != 0:
        Abnormal.append("SBP")
    if score_HR != 0:
        Abnormal.append("HR")
    if score_Temp != 0:
        Abnormal.append("Temp")
    

    elif 子句是else if。因此,当您的代码评估为 True 第一个时,它会忽略其余部分。这就是您没有得到预期结果的原因。

    【讨论】:

      【解决方案2】:

      你可以试试:

      score_Resp = 0
      score_O2Sat = 5
      score_SBP = 0
      score_HR = 1
      score_Temp = 0
      
      Abnormal = []
      if score_Resp != 0:
          Abnormal.append("Resp")
      if score_O2Sat != 0:
          Abnormal.append("O2Sat")
      if score_SBP != 0:
          Abnormal.append("SBP")
      if score_HR != 0:
          Abnormal.append("HR")
      if score_Temp != 0:
          Abnormal.append("Temp")
      
      print("Abnormal Vitals:", Abnormal)
      

      【讨论】:

        【解决方案3】:

        只有当你经历了每一个条件并想要检查它时才使用它。

        score_Resp = 0
        score_O2Sat = 5
        score_SBP = 0
        score_HR = 1
        score_Temp = 0
        
        Abnormal = []
        if score_HR != 0:
            Abnormal.append("HR")
        if score_O2Sat != 0:
            Abnormal.append("O2Sat")
        if score_SBP != 0:
            Abnormal.append("SBP")
        if score_Resp != 0:
            Abnormal.append("Resp")
        if score_Temp != 0:
            Abnormal.append("Temp")
        
        print("Abnormal Vitals:", Abnormal)
        

        【讨论】:

        • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
        猜你喜欢
        • 2016-11-19
        • 1970-01-01
        • 1970-01-01
        • 2018-02-08
        • 2021-11-23
        • 2021-12-21
        • 1970-01-01
        • 2018-08-10
        相关资源
        最近更新 更多