I'm trying to create a method in python, which accepts 1-n number of parameters, calls the same method on each and returns the result. For example;
(Note this is pseudo code, I'm just typing these methods/syntax on the fly - new to python )
def get_pid(*params):
pidlist = []
for param in params:
pidlist.add(os.getpid(param))
return pidlist
Ideally I would like to do something like
x, y = get_pid("process1", "process2")
Where I can add as many parameters as I want - and the method to be as 'pythonic' and compact as possible. I think there may be a better way than looping over the parameters and appending to a list?
Any suggestions/tips?
Your code already works. Your function accepts 0 or more arguments, and returns the results for each function call. There is but a minor mistake in it; you should use list.append()
; there is no list.add()
method.
You could use a list comprehension here to do the same work in one line:
def get_pid(*params):
return [os.getpid(param) for param in params]
You could just inline this; make it a generator expression perhaps:
x, y = (os.getpid(param) for param in ("process1", "process2"))
You could also use the map()
function for this:
x, y = map(os.getpid, ("process1", "process2"))
You can use yield to create a generator:
def get_pid(*params):
for param in params:
yield os.getpid(param)
x, y = get_pid("process1", "process2")
print(x, y)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With