如何简化循环和条件语句

4

有更好或更短的编写此代码的方式吗?

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']

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


1
由于在每个 if 中您都检查 code==1.0,因此您可以在 for 循环开始时仅检查一次,这样更有效率。 - Omri Attiya
输入列表是否保证有4个元素? - user202729
很好的问题@user202729。我甚至没有考虑过这个。在我的数据中,是保证有4个元素的。 - srisays
这些数字是浮点数(1.0)还是整数(1)? - Andrew Jaffe
6个回答

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

1
使用 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。 - user202729

1
该函数 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

1
您可以使用以下方式使用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']

0
你可以不用循环来完成这个操作,像这样:
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))

0

我写了一个带有错误处理的示例:

功能:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接