How to avoid hard coding in if condition of python script -
i new python. have query regarding un-hardcoding object names(if condition) in python script. have fruit = [ apple, mango, pineapple, banana, oranges] , size = [ small, medium , big] write code below:
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
how can avoid writing multiple if...else conditions?
statement 1: pulling dot file related fruit , size directory path structure main-directory/fruit/collateral/fruit_size.dot statement 2: pulling txt file related fruit , size directory path structure main-directory/source/readparamters/readparam/fruit_size.txt
i want execute statements each condition 1 @ time. take inputs fruit , size user. there way in python script can automatically take combinations 1 one , execute statements? know it's complex , python expert can me.
how using itertools.product
, handling errors try..catch
. https://docs.python.org/3/library/itertools.html#itertools.product
import itertools fruits = ['apple', 'mango', 'pineapple', 'banana', 'oranges'] sizes = ['small', 'medium', 'big'] 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 e: print(e) # handle erorrs!
or, check file existence os.path.isfile
without using 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
generates cartesian product of input iterables.
>>> 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')]
Comments
Post a Comment