I would like to store intermediate results from a nested list comprehension in sublists so that the result looks like this:
example_list = [[[1,2,3], [1,2,3]], [[2,3,4], [2,3,4]]];
sink = [];
for sl in example_list :
temp = [];
for ssl in sl :
temp.append(np.mean(ssl));
sink.append(temp);
expected_result = [[2,2], [3,3]];
How do you perform this using a list comprehension?
I tried something like this, but obviously it doesn't work, I'm blocked on the syntax:
sink = [[np.mean(j)] for i in example_list for j in i];
Not sure what the challenge is. You can create a nested loop within the list. comprehension and store the values.
Here's what I did:
x = [[[i*j*k for i in range (1,4)] for j in range(1,4)] for k in range(1,3)]
print (x)
Output is:
[[[1, 2, 3], [2, 4, 6], [3, 6, 9]], [[2, 4, 6], [4, 8, 12], [6, 12, 18]]]
If you can give me a good use case, it can be implemented.
In the meanwhile, let me see if I can grab some data and show you the implementation.
you can try this;
final_list=[[int(np.mean(ssl)) for ssl in sl] for sl in example_list]
print(final_list)
output:
[[2, 2], [3, 3]]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.