2013-12-17 474 views
0

我目前有一个脚本,它在循环中运行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中的特定位置。

+2

什么部分精确地困扰着你? –

+2

您的三个列表中的每一个都包含*一个*共享列表对象,三次。你可能不想要那样。 –

+0

复杂是你的代码(尤达大师)!只是开玩笑,但你为什么使用这么多的名单?既然你知道你在处理什么,恕我直言,你应该使用一个班级来更好地组织你正在处理的信息。 –

回答

0

如果我得到你所需要的,就像HugoCorrà所说的那样,使用类来使数据结构易于管理是很重要的。

或者,也许你可以使用类型的字典中的结构是这样的:

terminals = {'terminal_1': {'month_1': [list of data], 'month_2': [list of data]} etc..} 
terminals_sums = {'terminal_1': {'month_1': [sums], 'month_2': [sums]} etc..} 

这样,您可以使用终端[“终端_1”] [“MONTH_2”] [:]选择使用索引的数据你可以在terminals_sums字典中使用。

相关问题