Python根据数组键求和两列

时间:2018-07-25 14:07:08

标签: python

我有以下内容:

one

我需要根据“类型”列和NAID对RT和LT值求和,如下所示,对相同类型和NAID的值求和。

Type RT LT NAID RecordTime "T" "15" "123" "NZ45" "2018-05-30 16:59:00" "S" "34" "210" "NZ45" "2018-05-30 16:59:00" "T" "56" "480" "NZ45" "2018-05-30 16:59:00" "T" "90" "480" "CR98" "2018-05-30 16:59:00" "S" "80" "180" "RU992" "2018-05-30 16:58:00"

你能帮我吗?

1 个答案:

答案 0 :(得分:0)

我相信您的数据来自数据库,但已将其放入列表中以模拟效果。

rows = [["T","15","123","NZ45","2018-05-30 16:59:00"],
["S","34","210","NZ45","2018-05-30 16:59:00"],
["T","56","480","NZ45","2018-05-30 16:59:00"],
["T","90","480","CR98","2018-05-30 16:59:00"],
["S","80","180","RU992","2018-05-30 16:58:00"]]

rslts = {}
for Type,RT,LT,NAID,RecT in rows:
    # create a unique key for each combination of NAID, Type, and RecT
    key = "_".join([NAID, Type, RecT])

    if key in rslts:
         # we have seen this combination before: add LT and RT to the existing LT and RT
         rslts[key]["RT"] += int(RT)
         rslts[key]["LT"] += int(LT)  
    else:
        # if we haven't seen this combination before, add the record under the unique key
        rslts[key] = { "NAID": NAID, "RecT": RecT, "Type": Type, "RT": int(RT), "LT": int(LT) }

# print out the data
print( "\t".join( ['Type','RT','LT','NAID','RecT'] ) )
for k in rslts:
    print( "\t".join( map(lambda x: str(rslts[k][x]), ['Type','RT','LT','NAID','RecT'] ) ) )

输出:

Type    RT  LT  NAID    RecT
T       71  603 NZ45    2018-05-30 16:59:00
S       34  210 NZ45    2018-05-30 16:59:00
T       90  480 CR98    2018-05-30 16:59:00
S       80  180 RU992   2018-05-30 16:58:00

请注意,我必须将LT和RT转换为整数以执行加法运算,并转换为字符串以将其打印出来。如果LT和RT以整数形式出现在数据库中,则可能不需要执行此步骤。