Advertisement
Guest User

Pass list of lists of funcs & args, gen list of func(args)s

a guest
Feb 4th, 2019
145
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.67 KB | None | 0 0
  1. def divide(x, y):
  2.     return x / y
  3.  
  4. def multiply(x, y):
  5.     return x * y
  6.  
  7. def listolists2list_yo(func, *x):
  8.     '''
  9.    Take a list of function(s) and a list(s) of lists possibly containing dict(s), and
  10.    return function(*list) for each list in list for each function in list of functions.
  11.  
  12.    EXAMPLE: listolists2list_yo(["multiply", "divide"], [[1, 2], [3, 4]])
  13.    RETURNS: [[2, 12], [0.5, 0.75]]
  14.  
  15.    TODO: Allow arbitrary nesting of lists within lists.
  16.    '''
  17.     result = []
  18.     for f in func:
  19.         presult = []
  20.         for thing in x:
  21.             if type(thing) == list:
  22.                 for item in thing:
  23.                     if isinstance(item, list):
  24.                         eval(f"presult.append({f}(*item))")  # Ye boi
  25.                     elif isinstance(item, dict):
  26.                         eval(f"presult.append({f}(item.get('x'), item.get('y')))")
  27.                     else:
  28.                         presult.append("ERROR")  # Sick graceful recovery
  29.             elif type(thing) == dict:
  30.                 eval(f"presult.append({f}(thing.get('x'), thing.get('y')))")
  31.             else:
  32.                 presult.append("ERROR")
  33.         result.append(presult)
  34.     return result
  35.  
  36. dawg = [[10, 5], [8, 4]]  # Everything in dawg & dawg2:
  37. dawg2 = [[6, 3], [4,2]]   # x / y = 2
  38. catdic = {'y':2, 'x':1}   # "Backwards", 1 / 2 = .5
  39. catdic2 = {'y':4, 'x':3}  # 3 / 4 = .75
  40. listdic = [catdic, catdic2]  # List of dicts fuck ye
  41.  
  42. uberlist = [["divide", "multiply"], dawg, dawg2, catdic, listdic, (3,2)]
  43. for line in listolists2list_yo(*uberlist):
  44.     print(line)
  45.  
  46. '''OUTPUT
  47. [2.0, 2.0, 2.0, 2.0, 0.5, 0.5, 0.75, 'ERROR']
  48. [50, 32, 18, 8, 2, 2, 12, 'ERROR']
  49. '''
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement