在python中减少if条件以避免在单个函数中重复操作
我有下面的函数,其中我根据每个在python中减少if条件以避免在单个函数中重复操作,python,Python,我有下面的函数,其中我根据每个x\u id字符串的最后一个字符检查list\u文件的值。 对于每个if条件,我必须在单个函数中给出相同的操作才能返回 是否有一种方法可以根据x\u id一次性分配list\u文件的值,并避免重复相同的\u操作() 代码如下: def custm(x_code,x_id,x_date, list_of_files): x_code = self.getcode() x_id = self.getid() x_date =sel
x\u id
字符串的最后一个字符检查list\u文件的值。
对于每个if条件,我必须在单个函数中给出相同的操作才能返回
是否有一种方法可以根据x\u id
一次性分配list\u文件的值,并避免重复相同的\u操作()
代码如下:
def custm(x_code,x_id,x_date, list_of_files):
x_code = self.getcode()
x_id = self.getid()
x_date =self.getdate()
if list(x_id)[-1] == '0':
list_of_files = list_of_files[0]
some_operation()
return some_operation
if list(x_id)[-1] == '1':
list_of_files = list_of_files[1]
some_operation()
return some_operation
if list(x_id)[-1] == '2':
list_of_files = list_of_files[2]
some_operation()
return some_operation
if list(x_id)[-1] == '3':
list_of_files = list_of_files[3]
some_operation()
return some_operation
您可以只使用带有枚举的for循环
last_id = list(x_id)[-1]
for idx, number in enumerate("0123"):
if last_id == number:
list_of_files = list_of_files[idx]
some_operation()
return some_operation
由于您是从每个if语句返回的,因此不管这种更改如何,您只需分配一次
def custm(x_code,x_id,x_date, list_of_files):
x_code = self.getcode()
x_id = self.getid()
x_date =self.getdate()
if list(x_id)[-1] == '0':
list_of_files = list_of_files[0]
elif list(x_id)[-1] == '1':
list_of_files = list_of_files[1]
elif list(x_id)[-1] == '2':
list_of_files = list_of_files[2]
elif list(x_id)[-1] == '3':
list_of_files = list_of_files[3]
else
return
some_operation()
return some_operation
您可以直接将数字字符串转换为int,并使用它来索引。
为了确保它始终有效,您可能希望在中尝试<代码>捕获
插入以查找不起作用的案例
例:
some_操作方法独立于_文件列表?您的意思是返回一些_操作()
?您的意思是返回一些_操作()
?@DeepSpace-这与op的代码相同。。。由于它的伪代码,我选择将其保留为writenop,可能还需要一个条件,即i小于4,从这个问题上看还不太清楚
def custm(x_code,x_id,x_date, list_of_files):
x_code = self.getcode()
x_id = self.getid()
x_date =self.getdate()
i = int(list(x_id)[-1]) #cast the string of the number into the actual number
if i in range(1,5): #condition if list(x_id)[-1] can be bigger than 4
# as suggested by @FBruzzesi
list_of_files = list_of_files[i] # use the number
some_operation()
return some_operation