我目前有一個腳本,它在循環中運行SQL查詢,該循環遍歷三個終端,三個月用於季度報告。在每個循環之後,腳本將生成的SQL數據插入到基於終端的三個列表之一中,並在終端內插入三個月份列表中的一個。Python:遍歷列表並將數據插入到另一個列表中的特定位置
terminals = [terminal_1, terminal_2, terminal_3]
months = [month_1, month_2, month_3] #ex. 1, 2, 3 for Jan, Feb, Mar
terminal_1Totals = [[]]*3 #three nested lists for months
terminal_2Totals = [[]]*3
terminal_3Totals = [[]]*3
for t in terminals:
for m in months:
#do the query
#add results to terminal_tTotals for month m
#close current connection
經過上述運行,我剩下三個嵌套列表與三個月的價值數據。每個「月」列表中包含以下數據:
'terminalID', 'transactionNumber', 'year', 'month', 'date (YYMMDD)', 'productCode', 'transaction total'
到目前爲止,一切都很好...
我從這裏做什麼,是會爲每個終端列表,以及內列表中,三個名單是誰的長度由monthrange確定(年,monthN):
terminal1_sums = [[0]*monthrange(year, month_1)[1], [0]*monthrange(year, month_2)[1], [0]*monthrange(year, month_3)[1]]
terminal2_sums = [[0]*monthrange(year, month_1)[1], [0]*monthrange(year, month_2)[1], [0]*monthrange(year, month_3)[1]]
terminal3_sums = [[0]*monthrange(year, month_1)[1], [0]*monthrange(year, month_2)[1], [0]*monthrange(year, month_3)[1]]
我需要在這裏做的是遍歷'terminal_NTotals名單與產品代碼「12345」的所有交易,及基於'日期',列插入(+ =)交易代碼到相應的位置在'terminalN_sums'列表中。每個月有4000個條目,每天有多筆交易,因此我需要總結特定日期的所有交易總計,並將該總額插入到彙總列表中
如何迭代「總計」列表,並將必要的數據插入到terminalN_sum中的特定位置。
什麼部分精確地困擾着你? –
您的三個列表中的每一個都包含*一個*共享列表對象,三次。你可能不想要那樣。 –
複雜是你的代碼(尤達大師)!只是開玩笑,但你爲什麼使用這麼多的名單?既然你知道你在處理什麼,恕我直言,你應該使用一個班級來更好地組織你正在處理的信息。 –