0

I am looking to create a Excel/Google Sheet IFS() -like function in python where you can pass unlimited pairs of arguments:

def region_info(region_name1, region_list1, [region_name2, region_list2]...):
    # do something with each region_name and region_list passed

norcal_list = ["john", "ken", "ben"]
socal_list = ["amy", "dan", "jose"]

region_info("Norcal", norcal_list, "Socal", socal_list)

I am not sure what is the most elegant way to approach this in Python. Can this be achieved by simply passing *arg at the end or the arguments must be in **kwarg?

martineau
  • 119,623
  • 25
  • 170
  • 301
Vic
  • 617
  • 1
  • 8
  • 12
  • See https://stackoverflow.com/q/36901/3001761 – jonrsharpe Apr 08 '21 at 21:44
  • Does this answer your question? [What does \*\* (double star/asterisk) and \* (star/asterisk) do for parameters?](https://stackoverflow.com/questions/36901/what-does-double-star-asterisk-and-star-asterisk-do-for-parameters) – Reishin Apr 08 '21 at 21:55
  • As you suspect, using `*arg` is the right approach. In fact, your function should only accept `*arg`, without any other parameters. – Amitai Irron Apr 08 '21 at 22:20
  • What I am struggle with is if I have `def func(arg1, arg2, *args)` and I expect `arg1` to be a string and `arg2` to be a list, how do I write the function in a way that if `arg3` and `arg4` are passed in, the function would process `arg3` and `arg4` the same way it does for `arg1` and `arg2`? Do I simply write a `for` statement that process two elements in a list at a time? – Vic Apr 08 '21 at 23:44

1 Answers1

0

You would want to use *args to accept an arbitrarily long list of arguments as explained in the Arbitrary Argument Lists section of the Python Tutorial.

Here's an example of using it:

def ifs(*pairs):
    for expr, value in pairs:
        if eval(expr):
            return value
    else:
        return float('nan')


sheet = {'A': {'1': 3, '2': 13, '3': 52} ,
         'B': {'1': 8, '2': 6, '3': 4},
         'C': {'1': 37, '2': 24, '3': 1},}

print(ifs(["sheet['A']['2'] < sheet['B']['1']", 16],
          ["sheet['A']['1'] > sheet['C']['3']", 42]))  # -> 42
martineau
  • 119,623
  • 25
  • 170
  • 301