我下面有这个列表,我需要对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求和,但不能同时求和,使用下面的代码,上面的列表保存在名为"行"的变量中:
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
如果将defaultdict设置为int
,则只能为字典中的每个键存储一个整数。我不确定你是想对RT和LT求和,还是为每个生成单独的计数。
将RT和LT组合为一个值:
sumarized = defaultdict(int)
for Type,RT,LT,NAID,RecT in rows:
sumarized[NAID, RecT] += RT + LT
print(sumarized)
输出(格式化以便于阅读(:
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
})
为了将值分开,您需要在键中添加一些内容来区分两者:
for T,RT,LT,NAID,RecT in data:
sumarized[NAID, RecT, 'RT'] += RT
sumarized[NAID, RecT, 'LT'] += LT
print(sumarized)
输出(格式化以便于阅读(:
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
})
如果您想要其他类型的数据排列,您可以相应地更改defaultdict键/值/设置。