Counting positive integer elements in a list with Python list comprehensions

If you want to reduce the amount of memory, you can avoid generating a temporary list by using a generator: sum(x > 0 for x in frequencies) This works because bool is a subclass of int: >>> isinstance(True,int) True and True‘s value is 1: >>> True==1 True However, as Joe Golton points out in the … Read more

How can I count how many duplicates there are for each distinct value in sqlite?

My quick google with the terms “count unique values sqlite3” landed me on this post. However, I was trying to count the overall number of unique values, instead of how many duplicates there are for each category. From Chris’s result table above, I just want to know how many unique colors there are. The correct … Read more

Sum of items in a collection

You can do LINQ to Objects and the use LINQ to calculate the totals: decimal sumLineTotal = (from od in orderdetailscollection select od.LineTotal).Sum(); You can also use lambda-expressions to do this, which is a bit “cleaner”. decimal sumLineTotal = orderdetailscollection.Sum(od => od.LineTotal); You can then hook this up to your Order-class like this if you … Read more

Linq query with nullable sum

You want to use the nullable form of Sum, so try casting your value to a nullable: from i in Db.Items select new VotedItem { ItemId = i.ItemId, Points = (from v in Db.Votes where b.ItemId == v.ItemId select v.Points).Sum(r => (decimal?) r.Points) } Your issue is discussed here in more detail: http://weblogs.asp.net/zeeshanhirani/archive/2008/07/15/applying-aggregates-to-empty-collections-causes-exception-in-linq-to-sql.aspx

Sum range of int’s in List

You can accomplish this by using Take & Sum: var list = new List<int>() { 1, 2, 3, 4 }; // 1 + 2 + 3 int sum = list.Take(3).Sum(); // Result: 6 If you want to sum a range beginning elsewhere, you can use Skip: var list = new List<int>() { 1, 2, 3, … Read more

Summing elements in a list [duplicate]

You can sum numbers in a list simply with the sum() built-in: sum(your_list) It will sum as many number items as you have. Example: my_list = range(10, 17) my_list [10, 11, 12, 13, 14, 15, 16] sum(my_list) 91 For your specific case: For your data convert the numbers into int first and then sum the … Read more