Search code examples
pythonpython-3.xconditional-statementsany

Is there a short way to switch between 'any' and 'all' in condition in function?


I have a function where I check several list of parameters:

def check_function(some_input_parameters):
  #do_smth
  ...

  if all(bet_res[i] for i in res_number_list):
     good_row_list.append(row_dict)
  else:
     bad_row_list.append(row_dict)
  #do_smth
  ...

In some cases I need "all" and sometimes I need "any". Is there a nice short way to change all/any by some input param? I can do smth like this, but I don't like it:

if any_all_flag = 'all':
        if all(bet_res[i] for i in res_number_list):
            good_row_list.append(row_dict)
        else:
            bad_row_list.append(row_dict)
else:
        if any(bet_res[i] for i in res_number_list):
            good_row_list.append(row_dict)
        else:
            bad_row_list.append(row_dict)

Solution

  • The all and any functions accept iterables, so you don't need to loop over the iterator again, unless you only want to apply the functions on certain number of items. One neat approach here is to use a dictionary like following for preserve the function and their names so that you can access to the respective function by a simple indexing.

    functions = {'all': all,
                 'any': any}
    
    if functions[any_all_flag](bet_res):
        # do stuff