如何在python脚本的条件下避免硬编码

时间:2015-07-02 01:42:15

标签: python

我是python的新手。我有关于python脚本中的非硬编码对象名称(如果条件)的查询。 我有水果= [苹果,芒果,菠萝,香蕉,橘子] 和尺寸= [小,中,大] 目前我编写如下代码:

if (fruit == apple, size == small): 
   statement 1
   statement 2
elif (fruit == apple, size == medium):
   statement 1
   statement 2
elif (fruit == apple, size == big):
   statement 1
   statement 2
elif (fruit == Mango, size == small):
   statement 1
   statement 2
elif (fruit == Mango, size = medium):
   statement 1
   statement 2

如何避免编写多个if ... else条件?

声明1:从目录中提取与水果和大小相关的点文件 路径结构是 主目录/水果/抵押/ fruit_size.dot 声明2:从目录中提取与水果和大小相关的txt文件 路径结构是 main-directory / source / readparamters / readparam / fruit_size.txt

我想一次一个地执行每个条件的语句。目前我从用户那里获取水果和大小的输入。在python中有一种方法,脚本可以自动逐个组合并执行语句吗?我知道它有点复杂,python专家可以帮助我。

6 个答案:

答案 0 :(得分:7)

您可以创建值和函数的映射。例如

MAP = {'apples':{'small':function1,
                'large':function3},
      'oranges':{'small':function2}}
#Then Run it like so:
fruit = 'apples'
size = 'large'
result = MAP[fruit][size]()

这将使用水果和大小在字典中查找函数,然后运行它并将结果存储在结果中。这样,如果您需要添加其他水果或大小,您只需修改字典中的数据而无需更改任何代码。

编辑: 我刚看了你的更新。如果处理步骤相同且唯一改变的是文件的位置,我建议编写一个将水果和大小作为参数的函数,并根据输入打开文件。然后你可以用你想要的水果和大小来运行它,而不是疯狂的if语句。

答案 1 :(得分:2)

(我的第一个回答)

您可以将所有测试组合成一个条件:

if (fruit == apple and (size == small or size == medium or size == big)) or \
        (fruit == Mango and (size == small or size == medium)):
    statement 1
    statement 2

(原始海报澄清后的第二个答案)

写一个循环来检查是否满足条件,然后执行语句。

fruit = (...)  # From input
size  = (...)  # From input

found = False
known_fruits = ["apple", "mango"]  # Can be customized
known_sizes = ["small", "medium", "large"]  # Can be customized
for fr in known_fruits:
    for sz in known_sizes:
        if fruit == fr and size == sz:
            found = True
if found:
    statement 1
    statement 2

答案 2 :(得分:1)

如何使用itertools.product并使用try..catch处理错误。 https://docs.python.org/3/library/itertools.html#itertools.product

import itertools

fruits = ['Apple', 'Mango', 'Pineapple', 'Banana', 'Oranges']
sizes = ['small', 'medium', 'big']

for fruit, size in itertools.product(fruits, sizes):
    dot_file = 'main-directory/{fruit}/collateral/{fruit}_{size}.dot'.format(fruit=fruit, size=size)
    text_file = 'main-directory/source/readparamters/readparam/{fruit}_{size}.txt'.format(fruit=fruit, size=size)
    try:
        open(dot_file)  # statement 1
        open(text_file)  # statement 2
    except Exception as e:
        print(e)  # handle erorrs!

或者,在不使用os.path.isfile的情况下检查文件存在try..catch

import os
..
    dot_file = ..
    text_file = ..
    if os.path.isfile(dot_file):
        open(dot_file)  # statement 1
    if os.path.isfile(text_file):
        open(text_file)  # statement 2

itertools.product生成输入迭代的笛卡尔积。

>>> fruits = ['Apple', 'Mango', 'Pineapple', 'Banana', 'Oranges']
>>> sizes = ['small', 'medium', 'big']
>>> list(itertools.product(fruits, sizes))
[('Apple', 'small'), ('Apple', 'medium'), ('Apple', 'big'), ('Mango', 'small'), ('Mango', 'medium'), ('Mango', 'big'), ('Pineapple', 'small'), ('Pineapple', 'medium'), ('Pineapple', 'big'), ('Banana', 'small'), ('Banana', 'medium'), ('Banana', 'big'), ('Oranges', 'small'), ('Oranges', 'medium'), ('Oranges', 'big')]

答案 3 :(得分:0)

这实际上取决于你所拥有的陈述1和陈述2.
如果代码相似,那么有效的一件事就是将所有更改的常量提取到容器中,并使用dict来访问它们。

fruits = {
  'mango': {'color': 'orange'},
  'apple': {'color': 'red'},
   # ...
}
weights = {
  'apple': {
    'small': 100,
    'medium': 200,
    # ...
  }
  # ...
}

fruit = 'apple'
size = 'medium'

print "A %s %s is %s and weighs %ig" % (size, fruit, fruits[fruit]['color'], weights[fruit][size])
# => A medium apple is red and weighs 200g

答案 4 :(得分:0)

如果只使用水果名称和大小生成所有文件名:

def process_fruits(fruit, size, param):
    dot_file = "main-directory/{fruit_name}/collateral/{size}.dot"
    text_file = "main-directory/source/readparamters/{param}/{size}.txt"

    fruit = dict(fruit_name=fruit, size=size, param=param)

    paths = dict(dot=dot_file.format(**fruit), text=text_file.format(**fruit))

    # load paths['dot']
    # load paths['text']

您可以将其添加到函数中,以便在创建水果时获取路径。

fruits = ['apple', 'mango']

for fruit in fruits:
    for size in ['small', 'medium', 'big']:
        process_fruits(fruit, size, 10)

答案 5 :(得分:0)

Python遗憾的是没有切换案例,但您可以使用字典,如此问题的接受答案:

Replacements for switch statement in Python?