user1736554
user1736554

Reputation: 21

Finding the index and sum in a list of lists

Hello I have what I hope is an easy problem to solve. I am attempting to read a csv file and write a portion into a list. I need to determine the index and the value in each row and then summarize.

so the row will have 32 values...each value is a classification (class 0, class 1, etc.) with a number associated with it. I need a pythonic solution to make this work.

import os,sys,csv
csvfile=sys.argv[1]
f=open(csvfile,'rt')
reader=csv.reader(f)
classes=[]
for row in reader:
  classes.append(row[60:92])
f.close()

classes = [' ', '1234', '645', '9897'],  [' ', '76541', ' ', '8888']

how would i extract the index values from each list to get a sum for each? for example: 0=(' ', ' ') 1=('1234', '76541') 2= ('645', ' ') 3= ('9897', '8888') then find the sum of each

class 0 = 0
class 1 = 77775
class 2 = 645
class3 = 18785

Any assistance would be greatly appreciated

Upvotes: 2

Views: 365

Answers (3)

Rusty Rob
Rusty Rob

Reputation: 17203

You could sum as you go through the CSV file rows. (e.g. put the for class_ loop inside your rows loop) .. :

>>> classes
[[' ', '1234', '645', '9897'], [' ', '76541', ' ', '8888']]
>>> sums = {}
>>> for row in classes:
...     for class_, num in enumerate(row):
...         try:
...             num = int(num)
...         except ValueError:
...             num = 0
...         sums[class_] = sums.get(class_, 0) + num
...
>>> sums
{0: 0, 1: 77775, 2: 645, 3: 18785}

Upvotes: 0

Rusty Rob
Rusty Rob

Reputation: 17203

>>> classes = [[' ', '1234', '645', '9897'],  [' ', '76541', ' ', '8888']]
>>> my_int = lambda s: int(s) if s.isdigit() else 0
>>> class_groups = dict(zip(range(32), zip(*classes)))
>>> class_groups[1]
('1234', '76541')
>>> class_sums = {}
>>> for class_ in class_groups:
...     group_sum = sum(map(my_int, class_groups[class_]))
...     class_sums[class_] = group_sum
...
>>> class_sums[1]
77775
>>> class_sums[3]
18785
>>>

Upvotes: 0

wim
wim

Reputation: 363253

I find your use case a bit difficult to understand, but does this list comprehension give you some new ideas about how to solve your problem?

>>> classes = [' ', '1234', '645', '9897'],  [' ', '76541', ' ', '8888']
>>> [sum(int(n) for n in x if n != ' ') for x in zip(*classes)]
[0, 77775, 645, 18785]

Upvotes: 1

Related Questions