I have a list containing 100+ sublists. Need to get index wise maximum for this scenario using python.
L1= [3,2,7]
L2= [1,5,7]
L3= [10,3,6]
Get max value from index 0 of all lists
Get min value from index 1 of all lists
Get avg value from index 2 of all lists
Result list is [10,2,6.666]
I don't have further code, there are at least 100 such lists for which this calculation is required
I can share with you one approach
let us say there are only 2 lists.. you should try to extend this logic to 100 lists
L1: [2,8, 1]
L2: [3, 1, 6]
so the answer will be
[3,8,6]
to solve this make a list which will store the answer
ans = [0,0,0]
now iterate over every list and just replace every index with the largest value you see at that index
after first list ans will look like
[2,8,1]
coz all values are greater than zero
when you iterate over 2nd list, 3 is greater than 2 and 6 is greater than 1 so you just update them
and your answer will become
[3,8,6]
Pretty simple: https://numpy.org/
Transform your list of lists "LoL" into an array...
import numpy as np
LoL = np.asarray([L1, L2, L3])
...and then apply those aggregations...
Check the docs for details. Eg, "max": https://numpy.org/doc/stable/reference/generated/numpy.ndarray.max.html#numpy.ndarray.max
using zip():
Code:
L1= [3,2,7]
L2= [1,5,7]
L3= [10,3,6]
counter=0
res=[]
for lis in zip(L1,L2,L3): #It brings same index element together in the form of tuples [i.e (3, 1, 10),(2, 5, 3),(7, 7, 6)]
if counter==0:
res.append(max(lis))
counter+=1
elif counter==1:
res.append(min(lis))
counter+=1
else:
res.append(sum(lis)/len(lis)) #mean=sum_of_all_element/total_number_of_element
print(res) #Output [10, 2, 6.666666666666667]
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.