Issue
I have a python code like below:
import numpy as np
import multiprocessing as mp
def func(first, sec):
results = []
for x in range(first):
result_dict = {"a": x, "b": x**sec, "c": x/sec}
results.append(result_dict.copy())
return results
with mp.Pool(mp.cpu_count()) as pool:
res = pool.starmap(func, [(a, 8) for a in range(1, 4)])
Then I flatten the res
with this piece of code:
res = np.asarray(res)
res = res.reshape(-1)
res = np.array(res).tolist()
After that when I print the res
the output is like below:
[[{'a': 0, 'b': 0, 'c': 0.0}],
[{'a': 0, 'b': 0, 'c': 0.0}, {'a': 1, 'b': 1, 'c': 0.125}],
[{'a': 0, 'b': 0, 'c': 0.0},
{'a': 1, 'b': 1, 'c': 0.125},
{'a': 2, 'b': 256, 'c': 0.25}]]
But I want the output to be like this:
[{'a': 0, 'b': 0, 'c': 0.0},
{'a': 0, 'b': 0, 'c': 0.0},
{'a': 1, 'b': 1, 'c': 0.125},
{'a': 0, 'b': 0, 'c': 0.0},
{'a': 1, 'b': 1, 'c': 0.125},
{'a': 2, 'b': 256, 'c': 0.25}]
Do you have any idea how to change the code to get the desired result for res
?
Solution
The chain.from_iterable
of itertools
library lets you chain sub-lists to one list.
import itertools
res = [[{'a': 0, 'b': 0, 'c': 0.0}],
[{'a': 0, 'b': 0, 'c': 0.0}, {'a': 1, 'b': 1, 'c': 0.125}],
[{'a': 0, 'b': 0, 'c': 0.0},
{'a': 1, 'b': 1, 'c': 0.125},
{'a': 2, 'b': 256, 'c': 0.25}]]
print(list(itertools.chain.from_iterable(res)))
Answered By - Aviv Yaniv
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.