Python Forum

Full Version: Split List and Sublist from Pyodbc
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
My pyodbc returns cursor result as below
>>> result
[(Decimal('28000.0000'), 2010, 272), (Decimal('308000.0000'), 2011, 272), (Decimal('582000.0000'), 2012, 272), (Decimal('387000.0000'), 2013, 272), (Decimal('367000.0000'), 2010, 281), (Decimal('3037000.0000'), 2011, 281), (Decimal('4822000.0000'), 2012, 281), (Decimal('2936000.0000'), 2013, 281), (Decimal('637000.0000'), 2010, 282), (Decimal('3440000.0000'), 2011, 282), (Decimal('4415000.0000'), 2012, 282), (Decimal('3294000.0000'), 2013, 282), (Decimal('478000.0000'), 2010, 296), (Decimal('1209000.0000'), 2011, 296), (Decimal('478000.0000'), 2012, 296), (Decimal('1209000.0000'), 2013, 296)]
>>>
how to get data in list as below
Salesamount should split based on the year to sub list.

Salesamount = [[28000.00,308000.00,582000.00,387000.00],[367000.00,3037000.00,4822000.00,2936000.00],[637000.00,3440000.00,4415000.00,3294000.00],[478000.00,1209000.00,478000.00,1209000.00]]
CalendarYear = [2010,2011,2012,2013]
Employee = [272,281,282,296]
Also how to remove decimal as it is displaying as decimal in the list
>>> type(result)
<class 'list'>
The result you're showing is a list of tuples
so something like (you can build your lists from this (replace print with list creation code):
Decimal = float
results = [
    (Decimal('28000.0000'), 2010, 272), (Decimal('308000.0000'), 2011, 272),
    (Decimal('582000.0000'), 2012, 272), (Decimal('387000.0000'), 2013, 272),
    (Decimal('367000.0000'), 2010, 281), (Decimal('3037000.0000'), 2011, 281),
    (Decimal('4822000.0000'), 2012, 281), (Decimal('2936000.0000'), 2013, 281),
    (Decimal('637000.0000'), 2010, 282), (Decimal('3440000.0000'), 2011, 282),
    (Decimal('4415000.0000'), 2012, 282), (Decimal('3294000.0000'), 2013, 282),
    (Decimal('478000.0000'), 2010, 296), (Decimal('1209000.0000'), 2011, 296),
    (Decimal('478000.0000'), 2012, 296), (Decimal('1209000.0000'), 2013, 296)
]

for decimal, year, employee_id in results:
    print(f'\ndecimal: {decimal}\nYear: {year}\nEmployeeId: {employee_id}')
output:
Output:
decimal: 28000.0 Year: 2010 EmployeeId: 272 decimal: 308000.0 Year: 2011 EmployeeId: 272 decimal: 582000.0 Year: 2012 EmployeeId: 272 decimal: 387000.0 Year: 2013 EmployeeId: 272 decimal: 367000.0 Year: 2010 EmployeeId: 281 decimal: 3037000.0 Year: 2011 EmployeeId: 281 decimal: 4822000.0 Year: 2012 EmployeeId: 281 decimal: 2936000.0 Year: 2013 EmployeeId: 281 decimal: 637000.0 Year: 2010 EmployeeId: 282 decimal: 3440000.0 Year: 2011 EmployeeId: 282 decimal: 4415000.0 Year: 2012 EmployeeId: 282 decimal: 3294000.0 Year: 2013 EmployeeId: 282 decimal: 478000.0 Year: 2010 EmployeeId: 296 decimal: 1209000.0 Year: 2011 EmployeeId: 296 decimal: 478000.0 Year: 2012 EmployeeId: 296 decimal: 1209000.0 Year: 2013 EmployeeId: 296