Home > front end >  How to sum credit hours in a nested list
How to sum credit hours in a nested list

Time:04-11

I have a nested array. I need to get the sum of credit hours. The credit hours are in position [2] and [5] respectively. How do I achieve this using a for loop in python? I'm not conversant in Numpy.

marks = [   
    [ "MR. JONES", "ACCT203", 2, 3.0, "CIS100", 3, 2.5 ],
    [ "SKARE EEEY", "ACCT203", 2, 2.5, "BUS123", 2, 3.0 ],
    [ "HALO WEEN", "ACCT300", 5, 2.0, "ACCT301", 2, 1.5 ],
    [ "BOB KATZ", "ACCT300", 5, 1.0, "BUS278", 3, 4.0 ],
    [ "ANNIE BANANE", "ACCT300", 5, 0.0, "CIS223", 3, 1.5 ],
]

All I have managed to do is print them. I'm stuck beyond this.

for credit_hours in marks:
    cred_hours_part_one = credit_hours[2]
    cred_hours_part_two = credit_hours[5]
    print(cred_hours_part_one)
    print(cred_hours_part_two)

CodePudding user response:

The credit hours are in position [2] and [5] respectively.

So I assume you only want to sum the integers at indexes 2 and 5.

[ "MR. JONES", "ACCT203", 2, 3.0, "CIS100", 3, 2.5 ]

To get a single list from a nested list, you just have to take it from its index, for example:

>>> marks[0] # ...will give you...
[ "MR. JONES", "ACCT203", 2, 3.0, "CIS100", 3, 2.5 ]

So now you just have to sum its 2nd and 5th positions, for example:

>>> marks[0][2]   marks[0][5]
5

If you want to gather all the sums, you just have to use a list comprehension...

list_of_the_sums_of_the_marks = [mark[2]   mark[5] for mark in marks]

...and then to sum it...

sum(list_of_the_sums_of_the_marks)

I would suggest you to read something about nested lists.

CodePudding user response:

Just do this if you want the total sum:

total = sum([mark[2]   mark[5] for mark in marks])
print(total)
32

Or if you want the sum of every element in a nice dict:

results = {mark[0]: mark[2]   mark[5] for mark in marks}
print(results)
{'MR. JONES': 5, 'SKARE EEEY': 4, 'HALO WEEN': 7, 'BOB KATZ': 8, 'ANNIE BANANE': 8}
  • Related