簡體   English   中英

在RLE列表中的選定變量之間求平均,遇到最后一個元素的麻煩

[英]Averaging between select varibles on an RLE list, having trouble with the last element

因此,我使用游程長度編碼創建了一個壓縮列表。 現在,我試圖在列表中的某些變量(例如450180 )中找到平均值。 該代碼應該像這樣工作

 a=[[180,3],[140,1],[160,1],[150,2],[450,1][180,4]]
 print mean(a)
 >[[180,3],[150,4],[450,1][180,4]]

我對此很陌生,否則我將在壓縮過程中執行平均。

我所堅持的是兩件事:未壓縮時得到的結果列表與原始列表的長度不相同,並且我不確定如果代碼不通過最后一個元素,如何追加最后一個元素。 我可以在for循環中使用諸如elif i[0].index==len(lst)類的索引,但這在計算上會非常昂貴(數據集相當大)。 我創建的是for循環外的最終if語句,但是結果列表的長度仍然與原始長度不同。

def mean(lst):
    sm=0
    count=0
    new=[]
    for i in lst:
        if i[0] is None:
            new.append([0,1])  
        elif i[0]!=180.0 and i[0]!=450.0:
           sm+=(i[0]*i[1])
           count+=i[1]
        elif count==0:
           new.append(i)      
        else:
            new.append([sm/count,count])
            new.append(i)
            count=0
            sm=0 
    if count>0:
        new.append([sm/count,count])
    pass    
    return (new)

對於那些以后會研究該問題的人,我添加了將壓縮和平均相結合的解決方案。 為了闡明目的,我正在GIS程序中壓縮路段之間的角度以創建較小的數據集。 450可以視為空值。

with arcpy.da.SearchCursor("test_loop",["angle3"]) as cursor:
    count1 = 0
    count2=0
    count3=0
    add=0
    lst=[]
    for row in cursor:
        if row[0]<180 and row[0] is not None:
            if count1>0:
                lst.append([180,count1+count3])
                count1=0
                count3=0
                pass    
            count2+=1
            add+=row[0]
        elif row[0]==180:
            if count2>0:
                lst.append([add/count2,count2+count3])
                count2=0
                count3=0
                add=0
                pass    
            count1+=1    
        elif row[0]==450 or row[0] is None:
            count3+=1
        else:
            print "Error"
            break   
    if count1>0:
        lst.append([180,count1+count3])
        count1=0
        count3=0
    elif count2>0:
        lst.append([add/count2,count2+count3])
        count2=0
        count3=0
        add=0  
    else:
        lst.append([None,count3])                      
    print lst
    del cursor
    del row

def decode(lst):
   q = []
   for i in lst:
       for x in range(i[1]):
           q.append (i[0])
   return q   

final=decode(lst)
print final               

with arcpy.da.UpdateCursor("test_loop",["curve_level"]) as cursor:
    i=0
    for row in cursor:
        row[0]=final[i]
        i+=1
        cursor.updateRow(row)
del cursor
del row

假設您的輸出中不應有重復的條目180,並且您的預期輸出是:

[[180,7],[150,4],[450,1]]

我認為這可以做到:

from collections import defaultdict
def mean(lst):
    d = defaultdict(int)
    sm, count = 0.0, 0
    for [k, v] in lst:
        if float(k) in [180.0,450.0]:
            d[k] += v
        else:
            sm += k*v
            count +=v
    if sm != 0: d[sm/count] = count
    return [list(itm) for itm in d.items()]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM