python - 减少python中的if条件以避免单个函数中的重复操作

标签 python

我有下面的函数,我检查 list_of_files 的值基于每个 x_id 的最后一个字符字符串。
对于每个 if 条件,我必须在单个函数中给出相同的操作才能返回。

有没有办法分配 list_of_files 的值?曾经基于 x_id并避免重复 same_operation()
代码如下:

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

最佳答案

您可以只使用带有 enumerate 的 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 语句返回,因此无论如何您都只会分配一次,而不管此更改如何

关于python - 减少python中的if条件以避免单个函数中的重复操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59357270/

相关文章:

python - 用 Python 生成排序的足球联赛表

python - 对行匹配条件的列子集进行排序

python - Spark : How to parse and transform json string from spark data frame rows

python - 如何获取项目在列表中的位置?

python - python中的回归系数计算

python - 使用 Panda 每月平均每分钟时间序列数据集

python:传达缺失值计数的最佳方式

python - 使用两个不同的装饰器实现装饰所有类方法的元类

python - `subprocess.call` 与直接在 shell 中运行命令的操作不同

python - 如何去除列表中的 unicode