Python Forum
Insert into sublist if sublist is not having same no of records.
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Insert into sublist if sublist is not having same no of records.
#11
Pure-Python approach (taking advantage of else clause in for-loop):

results = [
    (28000.00, 2010, 272), (308000.00, 2011, 272),
    (582000.00, 2012, 272), (387000.00, 2013, 272),
    (367000.0000, 2010, 281), (3037000.00, 2011, 281),
    (4822000.00, 2012, 281), (2936000.00, 2013, 281),
    (637000.00, 2010, 282), (3440000.00, 2011, 282),
    (478000.00, 2010, 296), (1209000.00, 2012, 296)
    ]



calendar_year = list(set(sorted([row[-2] for row in results])))
employees = list(set(sorted([row[-1] for row in results])))

sales_amount = list()

for employee in employees:
    sales_amount.append([])
    for year in calendar_year:
        for row in results:
            
            if employee == row[-1] and year == row[-2]:
                    sales_amount[-1].append(row[0])
                    break
                
        else:       # no-break
            sales_amount[-1].append(0)
Output:
[2010, 2011, 2012, 2013] [272, 281, 282, 296] [[28000.0, 308000.0, 582000.0, 387000.0], [367000.0, 3037000.0, 4822000.0, 2936000.0], [637000.0, 3440000.0, 0, 0], [478000.0, 0, 1209000.0, 0]]
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Use one list as search key for another list with sublist of list jc4d 4 2,158 Jan-11-2022, 12:10 PM
Last Post: jc4d
Question Sublist/ Subarray into string Python SantiagoPB 2 2,126 Apr-23-2021, 07:03 PM
Last Post: SantiagoPB
  List of objects with sublist medatib531 4 2,315 Mar-01-2020, 06:16 PM
Last Post: buran
  Split List and Sublist from Pyodbc parthi1705 1 2,232 May-05-2019, 10:44 AM
Last Post: Larz60+
  merging sublist into single list in python abhishek8singhai 8 9,469 Mar-22-2019, 11:46 PM
Last Post: micseydel
  Can I use a sublist as an argument in python? MartinBerlin 3 3,982 Aug-25-2018, 10:46 AM
Last Post: buran
  Insert using psycopg giving syntax error near "INSERT INTO" olgethorpe 4 15,610 Jul-21-2017, 07:39 PM
Last Post: nilamo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020