繁体   English   中英

如何压缩循环,如果是的话

[英]How do I condense the loop and if else

是否有更好或更短的方式来编写此代码?

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

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

尝试使用:

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

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

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

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

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

功能:

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

你可以这样做,没有foor循环:

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))

暂无
暂无

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

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