【问题标题】:How do I condense the loop and if else我如何压缩循环以及如果其他
【发布时间】:2019-12-22 11:15:38
【问题描述】:

有没有更好或更短的方法来编写这段代码?

def business_role_code_to_name(x):
    y = []

    for position, code in enumerate(x):
        if position == 0 and code == 1.0: 
            y.append("Owner") 
        elif position == 1 and code == 1.0: 
            y.append("Manager")
        elif position == 2 and code == 1.0:
            y.append("Employee")
        elif position == 3 and code == 1.0:
            y.append("Other")
    return y

assert business_role_code_to_name([1.0, 1.0, 1.0, 0.0]) == ['Owner', 'Manager', 'Employee']
assert business_role_code_to_name([0.0, 1.0, 0.0, 1.0]) == ['Manager', 'Other']

我是编程新手,我认为编写此代码有更好的方法。谢谢!

【问题讨论】:

  • 因为在每个if 中检查code==1.0 您只需在for 循环的开头检查一次,这样效率更高
  • 是否保证输入列表有4个元素?
  • 好问题@user202729。我什至没有考虑。在我的数据中,是的,它保证有 4 个元素。
  • 这些数字是浮点数 (1.0) 还是整数 (1)?

标签: python for-loop if-statement


【解决方案1】:

尝试使用:

def business_role_code_to_name(x):
    y = []
    d = {(0, 1): 'Owner', (1, 1): 'Manager', (2, 1): 'Employee', (3, 1): 'Other'}
    for i in enumerate(x):
        if d.get(i):
            y.append(d[i])
    return y

【讨论】:

    【解决方案2】:

    使用itertools.compress:

    from itertools import compress
    
    names = ['Owner', 'Manager', 'Employee', 'Other']
    positions_0 = [1.0, 1.0, 1.0, 0.0]
    positions_1 = [0.0, 1.0, 0.0, 1.0]
    

    输出:

    list(compress(names, positions_0))
    # ['Owner', 'Manager', 'Employee']
    list(compress(names, positions_1))
    # ['Manager', 'Other']
    

    【讨论】:

    • 如果代码中的值不是 0 或 1 则需要检查 == 1。
    【解决方案3】:

    函数business_role_code_to_name与下面的逻辑相同

    def business_role_code_to_name(x):
        z = ['Owner', 'Manager', 'Employee' ,'Other']
        y = [z[position]  for position, code in enumerate(x) if code==1.0]
        return y
    

    【讨论】:

      【解决方案4】:

      您可以通过以下方式使用zip 执行该任务:

      roles = ["Owner","Manager","Employee","Other"]
      code1 = [1.0, 1.0, 1.0, 0.0]
      code2 = [0.0, 1.0, 0.0, 1.0]
      def decode_role(rolecode):
          return [role for code,role in zip(rolecode,roles) if code==1.0]
      print(decode_role(code1)) # ['Owner', 'Manager', 'Employee']
      print(decode_role(code2)) # ['Manager', 'Other']
      

      【讨论】:

        【解决方案5】:

        我写了一个错误处理的例子:

        功能:

        def business_role_code_to_name(x):
            y = []
            positions = {0: "Owner", 1: "Manager", 2: "Employee", 3: "Other"}
            for position, code in enumerate(x):
                if code != 1.0:
                    continue
                try:
                    y.append(positions[position])
                except KeyError as key_err:
                    print("{} is a wrong index.".format(position))
                    raise key_err
            return y
        

        测试:

        print(business_role_code_to_name([1.0, 1.0, 1.0, 0.0]))
        print(business_role_code_to_name([0.0, 1.0, 0.0, 1.0]))
        print(business_role_code_to_name([0.0, 1.0, 0.0, 1.0, 1.0]))
        

        输出:

        >>> python3 test.py 
        ['Owner', 'Manager', 'Employee']
        ['Manager', 'Other']
        4 is a wrong index.
        Traceback (most recent call last):
          File "test.py", line 21, in <module>
            print(business_role_code_to_name([0.0, 1.0, 0.0, 1.0, 1.0]))
          File "test.py", line 11, in business_role_code_to_name
            raise key_err
          File "test.py", line 8, in business_role_code_to_name
            y.append(positions[position])
        KeyError: 4
        

        【讨论】:

          【解决方案6】:

          你可以这样做,不用 foo 循环:

          roles = ('Owner', 'Manager', 'Employee', 'Other')
          def business_role_code_to_name(x):
              positions = filter(lambda k: x[k] == 1.0, range(len(x)))
              return list(map(roles.__getitem__, positions))
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2015-07-03
            • 2015-06-21
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2019-04-21
            • 1970-01-01
            相关资源
            最近更新 更多