I have this function:
import concurrent.futures
def function_abc(a,b):
#do something
I call this function with this:
with concurrent.futures.ThreadPoolExecutor() as executor:
executor.map(function_abc, a, b)
But this does not work.
If I remove the argument "b":
with concurrent.futures.ThreadPoolExecutor() as executor:
executor.map(function_abc, a)
It works anyway. But I don't get the additional argument inside of this function.
What am I doing wrong?
CodePudding user response:
Pass your arguments as separate iterables, one for a
and another for b
:
In [2]: with concurrent.futures.ThreadPoolExecutor() as ex:
...: m = ex.map(pow, (2, 2, 2, 2), (2, 3, 4, 5))
...:
...: for item in m:
...: print(item)
...:
4
8
16
32
To be more explicit:
ex.map(func_of_a_and_b, (a1, a2, a3, a4, ...), (b1, b2, b3, b4, ...))
CodePudding user response:
You can pass in a list of tuples instead. Tuples are defined as (a, b, c...) and cannot be modified, but you can access them the same as lists (with an index, reverse index, slicing).
So basically nested lists but python somelist = [sometuple, sometuple, sometuple]
For example:
## Lets say this function multiplies a and b
# This is a compact and fast way
def function_abc(tup):
return tup[0]*tup[1]
## This makes it possible to modify the variables (not the tuple) and a bit nicer for more complicated code
## This also has lists
def function_abc(tup):
a = tup[0]
b = tup[1]
a = a/2
#tup[0] = tup[0]/2 <- Will show error as tuples are immutable
return a*b
def combine(a, b):
if len(a) != len(b):
print("Wrong lengths!")
l = []
for i in range(0, len(a)):
l.append((a[i], b[i]))
return l
## In map:
a = [1, 2, 3]
b = [10, 9, 8]
results = list(map(function_abc, combine(a, b))) # Should work
print(results)
Note that you will need a combine function to combine the 2 lists into a list of tuples
EDIT: Fixed code with combine function. What was I thinking?