[英]How to simplify my elif code in python
I am viswa.我是维斯瓦。 I prepared a simple code using elif command.我使用 elif 命令准备了一个简单的代码。 I will share the code and condition... it is working.我将分享代码和条件......它正在工作。 but I am looking for simplified program.但我正在寻找简化的程序。 if anything available for the same result如果有任何可用于相同的结果
inputs names are= 'AEX_ABC','AEX_XXX','AEX_YYY','CAI_XXX','CAI_YYY'....etc., output should be AEX_1,AEX_2,AEX_3,CAI_1,CAI_2,....输入名称是 = 'AEX_ABC','AEX_XXX','AEX_YYY','CAI_XXX','CAI_YYY'....等,输出应为 AEX_1,AEX_2,AEX_3,CAI_1,CAI_2,....
program:程序:
name=(<user input>)
AEX,CAI,CAR,CCA,CEL,CLM,CRE,ECH,FAV,FRE,GMP,INS,ROU,TAR,TAV,UAV,VEH,ERROR=0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
name=part._name.split('_')
if name[0]=='AEX':
AEX+=1
i=AEX
elif name[0]=='CAI':
CAI+=1
i=CAI
elif name[0]=='CAR':
CAR+=1
i=CAR
elif name[0]=='CCA':
CAR+=1
i=CCA
elif name[0]=='CEL':
CEL+=1
i=CEL
elif name[0]=='CLM':
CLM+=1
i=CLM
elif name[0]=='CRE':
CRE+=1
i=CRE
elif name[0]=='ECH':
ECH+=1
i=ECH
elif name[0]=='FAV':
FAV+=1
i=FAV
elif name[0]=='FRE':
FRE+=1
i=FRE
elif name[0]=='GMP':
GMP+=1
i=GMP
elif name[0]=='INS':
INS+=1
i=INS
elif name[0]=='ROU':
ROU+=1
i=ROU
elif name[0]=='TAR':
TAR+=1
i=TAR
elif name[0]=='TAV':
TAV+=1
i=TAV
elif name[0]=='UAV':
UAV+=1
i=UAV
elif name[0]=='VEH':
VEH+=1
i=VEH
else:
ERROR+=1
i='error'+str(ERROR)
output=name[0]+i
print(output)
You can replace this with a dictionary lookup.您可以将其替换为字典查找。
stock_indices={<all stock indices:0>}
error=0
try:
stock_indices[input[0]]+=1
except KeyError:
error+=1
As Jesse Bakker says, this is a job for a dictionary.正如 Jesse Bakker 所说,这是一本字典的工作。 Whenever you find yourself creating a whole bunch of variable names to track a group of related items you should probably be using a dictionary instead.每当您发现自己创建了一大堆变量名来跟踪一组相关项目时,您可能应该改用字典。 You can use a dict
literal to initialize the dictionary, but when all of the items have the same initial value it's convenient to use the dict.fromkeys
class method, as shown below.您可以使用dict
文字来初始化字典,但是当所有项目具有相同的初始值时,使用dict.fromkeys
类方法会很方便,如下所示。
To keep the code lines short I've split the keys
string into two strings: Python will automatically join adjacent string literals, but we need to wrap the expression with parentheses so that the parser knows that it continues over more than one line.为了保持代码行简短,我将keys
字符串分成两个字符串:Python 将自动连接相邻的字符串文字,但我们需要用括号将表达式包装起来,以便解析器知道它继续超过一行。
keys = ('AEX,CAI,CAR,CCA,CEL,CLM,CRE,ECH,FAV,FRE,'
'GMP,INS,ROU,TAR,TAV,UAV,VEH,ERROR'.split(','))
stock_indices = dict.fromkeys(keys, 0)
def update_stock(name):
key = name.partition('_')[0]
if key not in stock_indices:
key = 'ERROR'
val = stock_indices[key] + 1
stock_indices[key] = val
return key, val
# Test
test = (
'AEX_ABC',
'AEX_XXX',
'AEX_YYY',
'BAD_ZZZ',
'CAI_XXX',
'CAI_YYY',
)
for name in test:
key, val = update_stock(name)
print('{0}_{1}'.format(key, val))
output输出
AEX_1
AEX_2
AEX_3
ERROR_1
CAI_1
CAI_2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.