Skip to main content
 首页 » 编程设计

python平均出列表中的列

2025年05月04日14lovecherry

我有四个具有相同 len

的列表
list1=[26, 26, 26, 27, 27, 27, 27, 28, 28, ..., 100, 100, 100] 
list2=[-1, -2, 10, 14, 13, 15, 20, -4, -10,...., 90, 10,  -1] 
list3=[11, 12, -3, -4, 10, 11, 12, 13, 14, ..., -1, -1, -1] 
list4=[50, 60, 70, 90, 30, 40, 20, 20, 10, ...., 20, 20, 20] 

我必须对 list2、3 和 4 中的值进行平均,它们在 list1 中共享相同的值。我的意思是,例如,对于 list2,我想要 (-1+-2+10)/3=2.33 因为 的相应元素list1 中的 -1、-2 和 10 为 26。 (14+13+15+20)/4=15.5(list1对应4个27)本质上,同样的思路也适用于list3和list4。对于 list3,我想要 (11+12+-3)/3=6.67

最终,经过变换和平均后,4个列表是:

list1=[26, 27, 28, ...., 100] 
list2=[2.33, 15.5, -7, ..., 33] 
list3=[6.667, 7.25, 13.5,.., -1] 
list4=[60, 45, 15, ..., 20] 

我正在考虑这样的事情。肯定有更优雅的方法来做到这一点。

for x, y, z, q in zip(list1, list2, list3, list4): 
    if x==previous x: 
       #same x, add y, z, q, to separate temp lists (when new x appears, average out) 
    else: 
       #new x, average out y, z, q (empty temp lists)    

请您参考如下方法:

假设第一个列表已经排序,你可以做这样的事情来平均其他列表中的数字对应于列表 1 中的相同数字:

list1=[26, 26, 26, 27, 27, 27, 27, 28, 28, 100, 100, 100] 
list2=[-1, -2, 10, 14, 13, 15, 20, -4, -10, 90, 10,  -1] 
list3=[11, 12, -3, -4, 10, 11, 12, 13, 14, -1, -1, -1] 
list4=[50, 60, 70, 90, 30, 40, 20, 20, 10, 20, 20, 20] 
 
# Transformed Lists 
list1_new = [] 
list2_new = [] 
list3_new = [] 
list4_new = [] 
 
def populate_new_list(): 
    list1_new.append(list1[start_index]) 
    # If using python 3, we don't need to convert int to float before division 
    list2_new.append( float(sum(list2[start_index:end_index+1])) / float((end_index-start_index+1)) ) 
    list3_new.append( float(sum(list3[start_index:end_index+1])) / float((end_index-start_index+1)) ) 
    list4_new.append( float(sum(list4[start_index:end_index+1])) / float((end_index-start_index+1)) ) 
 
start_index = 0 # Start index of same number in first list 
end_index = 0 # End index of same number in first list 
previous_item = list1[0] # Initialize previous_item with first item in the list 
 
# Iterate through the first list and store start and end index of duplicate numbers, then use populate_new_list to average those numbers. 
for index, item in enumerate(list1): 
    if previous_item == item: 
        end_index = index 
    else: 
        populate_new_list() 
        start_index = index 
        end_index = index 
        previous_item = list1[index] 
 
# Call populate_new_list once more after iterating through list1 to populate lists with last same number in list1 
populate_new_list() 
 
print(list1_new) # [26, 27, 28, 100] 
print(list2_new) # [2.3333333333333335, 15.5, -7.0, 33.0] 
print(list3_new) # [6.666666666666667, 7.25, 13.5, -1.0] 
print(list4_new) # [60.0, 45.0, 15.0, 20.0]