数组中重复键的Python Sum值

时间:2018-07-25 02:41:36

标签: python

我在下面有此列表,我需要对RT和LT值求和:

Type   RT     LT     NAID   RecordTime
"T"   "15"  "123"   "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"

我能够对RT求和,但不能同时对两者进行求和,使用下面的代码,上面的列表保存在名为“ rows”的变量中:

class tmonCon():
timeNow = datetime.datetime.now()
def setup_logger(name, log_file, level=logging.DEBUG):
    formatter = logging.Formatter(' %(levelname)s %(message)s')
    handler = logging.FileHandler('C:\\config\\' + log_file)
    handler.setFormatter(formatter)
    logger = logging.getLogger(name)
    logger.setLevel(level)
    logger.addHandler(handler)

    return logger

# conection to the database to get the Webtmon details
try:
    connect = psycopg2.connect("dbname='TMONNETWarehouse' user='postgres' 
 host='localhost' password='$$$$$$$'")
except:
    print ("I am unable to connect to the database")
# Read the db and assign the details to a variable
cur = connect.cursor()
cur.execute("""SELECT "Type","Realtime", "LowerBoundary", "NAID", "RecordTime" FROM "Boundaries" """)
rows = cur.fetchall()
logSearch = setup_logger('tmonSearch', 'tmonSearch')
for row in (rows):
    logSearch.info(', '.join ((str(r) for  r in row))) 

sumarized = defaultdict(int)
for T,R,L,NAID,RT in rows:
    sumarized[NAID, T, RecT] +=RT
print(sumarized)

这适用于RT,但我也需要总结LT

sumarized = defaultdict(int)
for Type,RT,LT,NAID,RecT in rows:
    sumarized[NAID, RecT] +=RT, =+LT

这不起作用,我不确定该如何总结RT和LT

1 个答案:

答案 0 :(得分:0)

If you're setting your defaultdict to int, you can only store an integer for each key in the dictionary. I'm not sure if you want to sum RT and LT, or generate separate counts for each.

To combine RT and LT as a single value:

sumarized = defaultdict(int)
for Type,RT,LT,NAID,RecT in rows:
    sumarized[NAID, RecT] += RT + LT
print(sumarized)

output (formatted for easier reading):

defaultdict(<class 'int'>, {
  ('NZ45', '2018-05-30 16:59:00'): 674,
  ('CR98', '2018-05-30 16:59:00'): 570,
  ('RU992', '2018-05-30 16:58:00'): 260
})

To keep the values separate, you'll need to add something to the keys to distinguish between the two:

for T,RT,LT,NAID,RecT in data:
    sumarized[NAID, RecT, 'RT'] += RT
    sumarized[NAID, RecT, 'LT'] += LT
print(sumarized)

output (formatted for easier reading):

defaultdict(<class 'int'>, {
  ('NZ45', '2018-05-30 16:59:00', 'RT'): 71, 
  ('NZ45', '2018-05-30 16:59:00', 'LT'): 603,
  ('CR98', '2018-05-30 16:59:00', 'RT'): 90,
  ('CR98', '2018-05-30 16:59:00', 'LT'): 480,
  ('RU992', '2018-05-30 16:58:00', 'RT'): 80,
  ('RU992', '2018-05-30 16:58:00', 'LT'): 180
})

If you want some other type of data arrangement you can alter your defaultdict keys/value/set up accordingly.