Middle items in a sublist

I have a list created by an iterative process consisting of a variable number of sub-lists of all of them with the same number of elements; which is also variable. For example, in one iteration, I can have 4 sublists of 3 elements each, for example:

list_1 = [[1,3,5], [7,4,9], [3,6,2], [5,4,7]] 

and in the next iteration of the code, I can:

 list_2 = [[2,4,8,3,5], [2,4,9,1,3], [1,9,6,3,6]] 

those. 3 sublist of 5 items.

For this iteration, all the sublist letters will always have the same number of elements.

I need a way to generate for iteration i new list from list_i containing the average value of all elements located at the same position in each sublist. So in the first case for list_1 I get:

 avrg_list = [4.0, 4.25, 5.75] 

and in the second case for list_2 :

 avrg_list = [1.67, 5.67, 7.67, 2.33, 4.67] 

How can I do this with flexible code that will tune to a different number of subscriptions and items?

+4
source share
2 answers

Interested in using numpy?

 In [19]: list_1 = [[1,3,5], [7,4,9], [3,6,2], [5,4,7]] In [22]: np.mean(list_1, 0) Out[22]: array([ 4. , 4.25, 5.75]) 
+5
source

Use zip with * :

 >>> [sum(x)/float(len(x)) for x in zip(*list_1)] [4.0, 4.25, 5.75] >>> [sum(x)/float(len(x)) for x in zip(*list_2)] [1.6666666666666667, 5.666666666666667, 7.666666666666667, 2.3333333333333335, 4.666666666666667] 

From docs :

zip() in combination with the * operator can be used to unpack the list.

 >>> zip(*list_1) [(1, 7, 3, 5), (3, 4, 6, 4), (5, 9, 2, 7)] 

Time comparison:

 >>> from itertools import izip >>> import numpy as np >>> lis = list_1*1000 >>> arr = np.array(lis) >>> %timeit np.mean(lis, 0) 10 loops, best of 3: 31.9 ms per loop >>> %timeit np.mean(arr, 0) 1000 loops, best of 3: 221 us per loop #clear winner >>> %timeit [sum(x)/float(len(x)) for x in zip(*lis)] 100 loops, best of 3: 826 us per loop #itertools.izip is memory efficient. >>> %timeit [sum(x)/float(len(x)) for x in izip(*lis)] 100 loops, best of 3: 881 us per loop 
+4
source

Source: https://habr.com/ru/post/1499837/


All Articles