【发布时间】: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