Discussions

python - Sum a list of object attributes - Stack Overflow
Communities for your favorite technologies. Explore all Collectives · Ask questions, find answers and collaborate at work with Stack Overflow for Teams More on stackoverflow.com
🌐 stackoverflow.com
July 1, 2015
Python - Sum by Unique Attributes in a List of Attributes - Stack Overflow
Communities for your favorite technologies. Explore all Collectives · Ask questions, find answers and collaborate at work with Stack Overflow for Teams More on stackoverflow.com
🌐 stackoverflow.com
July 25, 2018
python - List of Objects: Efficiently getting a list of sum of ith attribute - Stack Overflow
Sorry if the title is confusing, I don't know how to really word this problem well. I'm fairly new to programming outside of class projects/work, and I'm trying to develop good programming habits,... More on stackoverflow.com
🌐 stackoverflow.com
What's the most concise way in Python to group and sum a list of objects by the same property - Stack Overflow
sblom's answer works for hashable c.Y attributes, with minimal extra space (because it computes the sums directly). philhag's answer is basically the same as sblom's, but uses more auxiliary memory by making a list of each of the cs -- effectively doing what groupby does, but with hashing instead ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Python Forum
python-forum.io › thread-19819.html
How do I sum instance attributes?
Say I have a bunch of instances of a class and one of the attributes below is the salary for every player. How would I calculate the sum of the salary for all players every time an instance is created? Player1 = Player('John Smith','RB',749912,23) P...
Top answer
1 of 6
10

The defaultdict approach is probably better, assuming c.Y is hashable, but here's another way:

from itertools import groupby
from operator import attrgetter
get_y = attrgetter('Y')
tuples = [(y, sum(c.Z for c in cs_with_y) for y, cs_with_y in 
           groupby(sorted(cs, key=get_y), get_y)]

To be a little more concrete about the differences:

  • This approach requires making a sorted copy of cs, which takes O(n log n) time and O(n) extra space. Alternatively, you can do cs.sort(key=get_y) to sort cs in-place, which doesn't need extra space but does modify the list cs. Note that groupby returns an iterator so there's not any extra overhead there. If the c.Y values aren't hashable, though, this does work, whereas the defaultdict approach will throw a TypeError.

    But watch out -- in recent Pythons it'll raise TypeError if there are any complex numbers in there, and maybe in other cases. It might be possible to make this work with an appropriate key function -- key=lambda e: (e.real, e.imag) if isinstance(e, complex) else e seems to be working for anything I've tried against it right now, though of course custom classes that override the __lt__ operator to raise an exception are still no go. Maybe you could define a more complicated key function that tests for this, and so on.

    Of course, all we care about here is that equal things are next to each other, not so much that it's actually sorted, and you could write an O(n^2) function to do that rather than sort if you so desired. Or a function that's O(num_hashable + num_nonhashable^2). Or you could write an O(n^2) / O(num_hashable + num_nonhashable^2) version of groupby that does the two together.

  • sblom's answer works for hashable c.Y attributes, with minimal extra space (because it computes the sums directly).

  • philhag's answer is basically the same as sblom's, but uses more auxiliary memory by making a list of each of the cs -- effectively doing what groupby does, but with hashing instead of assuming it's sorted and with actual lists instead of iterators.

So, if you know your c.Y attribute is hashable and only need the sums, use sblom's; if you know it's hashable but want them grouped for something else as well, use philhag's; if they might not be hashable, use this one (with extra worrying as noted if they might be complex or a custom type that overrides __lt__).

2 of 6
10
from collections import defaultdict
totals = defaultdict(int)
for c in cs:
  totals[c.Y] += c.Z

tuples = totals.items()
🌐
Reddit
reddit.com › r/python › how do i do this?
r/Python on Reddit: How do I do this?
December 2, 2014 -

Hey guys, I'm learning Python on code academy and I'm stuck on this question. What am I doing wrong?

  1. Write a function average that takes a list of numbers and returns the average.

  2. Define a function called average that has one argument, numbers.

  3. Inside that function, call the built-in sum() function with the numbers list as a parameter. Store the result in a variable called total.

  4. Like the example above, use float() to convert total and store the result in total.

  5. Divide total by the length of the numbers list. Use the built-in len() function to calculate that.

  6. Return that result.

Is this right?

def average(numbers): total = numbers.sum() total = float(total) return len(total)

I don't know how to add indentation on this thing but assume there is one.

Find elsewhere
🌐
YouTube
youtube.com › how to fix your computer
PYTHON : Sum / Average an attribute of a list of objects - YouTube
PYTHON : Sum / Average an attribute of a list of objects [ Gift : Animated Search Engine : https://www.hows.tech/p/recommended.html ] PYTHON : Sum / Average
Published: December 6, 2021
Views: 34
🌐
Codecademy
codecademy.com › forum_questions › 519b8466281ab3668d0033f8
My code passes, but it doesn't actually work. | Codecademy
The error ‘list’ object has ... an attribute sum of object student[“???”]. Where the usage is sum(list). Take a look at the Python manual here: http://docs.python.org/3.3/library/functions.html#sum ... It worked! Below is my code, I did what you suggested and the code passed! def average(numbers): total = sum(numbers) result = float(total)/len(numbers) return result ... You need to multiply student[“tests”].sum() by .6 instead ...
🌐
Blender Artists
blenderartists.org › game engine › game engine support and discussion
python sum specific property on a list of objects - Game Engine Support and Discussion - Blender Artists Community
December 2, 2013 - import bge def main(): cont = bge.logic.getCurrentController() own = cont.owner sensDamage = cont.sensors['CollisionDamage'] actuHit = cont.actuators['Hit'] if sensDamage.positive: actuHit.value = sensDamage.hitObject['Damager'] cont.activate(actuHit) else: cont.deactivate(actuHit) main() this is used to calculate the damage done to a character in the game.
🌐
Stack Overflow
stackoverflow.com › questions › 71899071 › how-do-i-get-the-sum-of-specific-attributes-from-objects-in-a-list
python - How do I get the sum of specific attributes from objects in a list? - Stack Overflow
April 17, 2022 - If you want to have both combined, simply modify the code by removing a variable and adding both tile.soil and tile.water to the combined sum. There are more advanced ways to do it, using the sum function like in J_H's answer, or even using map and operator.attrgetter shenanigans, but it's not really worth it at your level of Python proficiency seems to be.
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-program-to-find-sum-of-elements-in-list
Find sum of elements in List - Python - GeeksforGeeks
By manually iterating over the list, you can accumulate the sum step by step. ... Explanation: For loop iterates through each element in the list, adding it to res in each step until all elements are summed. List comprehension allows you to create a new list based on an existing one and then use sum() to calculate the total. This is a more Pythonic way to do things when you want to transform the list first.
Published: August 13, 2026
🌐
W3Schools
w3schools.com › python › ref_func_sum.asp
Python sum() Function
Remove List Duplicates Reverse ... Study Plan Python Interview Q&A Python Training ... The sum() function returns a number, the sum of all items in an iterable....