Reputation: 43
Say I have a function that calculates and returns an value:
h = 4.13566733*10**-15
c = 2.99792458*10**(8+9)
def func(x):
for i in w:
A = h*c/i
return A
w = [1]
print func(w)
Fine. But if w is a larger array, say:
w = [1 ,2, 3, 4]
The func returns for the last value in w (4). Understandebly as that is the last item in the for-loop. But how can I make the func return an array with all 4 values, something like:
[1239, 619, 413, 309]
??
Upvotes: 1
Views: 64
Reputation: 6737
You can use map
, for example.
h = 4.13566733*10**-15
c = 2.99792458*10**(8+9)
def func(x):
return h*c/x
w = [1,2,3]
print map(func, w)
Will return [1239.8418743309974, 619.9209371654987, 413.2806247769991]
And you can use more elegant way (as for me):
h = 4.13566733*10**-15
c = 2.99792458*10**(8+9)
w = [1,2,3]
result = map(lambda (x): h*c/x, w)
Is returns also [1239.8418743309974, 619.9209371654987, 413.2806247769991].
Upvotes: 0
Reputation: 55942
this is similar to what at @mu posted, but it seems like your function is operating on single values that are not connected together and might be more flexible implemented as only taking a number as a param.
h = 4.13566733*10**-15
c = 2.99792458*10**(8+9)
def func(x):
return h*c / x
w = [1,2,3,4]
print([func(x) for x in w])
Upvotes: 1
Reputation: 50540
Make your A
a list and append each result to that list
h = 4.13566733*10**-15
c = 2.99792458*10**(8+9)
def func(x):
A = []
for i in w:
A.append(h*c/i)
return A
w = [1,2,3,4]
print func(w)
This outputs:
[1239.8418743309974, 619.92093716549869, 413.2806247769991, 309.96046858274934]
Upvotes: 1
Reputation: 76847
Python supports passing multiple arguments, and returning multiple values. That said, you can change your code to:
def func(w):
return [h*c/i for i in w]
If you now call this, you can get the required array:
>>> w = [1 ,2, 3, 4]
>>> func(w)
[1239.8418743309974, 619.9209371654987, 413.2806247769991, 309.96046858274934]
As for calling with multiple arguments and returning multiple examples, consider the following example method, which takes 2 inputs and returns 3 outputs:
>>> def get_product_modulo_dividend(x, y):
... return x*y, x%y, x/y
>>> get_product_modulo_dividend(100, 10)
(1000, 0, 10)
Upvotes: 3