简体   繁体   English

在列表列表中查找索引和总和

[英]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. 我正在尝试读取一个csv文件并将一部分写入列表。 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. 因此该行将具有32个值...每个值都是一个分类(类别0,类别1等),并带有与之关联的数字。 I need a pythonic solution to make this work. 我需要一个pythonic解决方案来完成这项工作。

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 例如:0 =('','')1 =('1234','76541')2 =('645','')3 =('9897','8888')然后找到每个的和

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

Any assistance would be greatly appreciated 任何帮助将不胜感激

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]
>>> 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
>>>

You could sum as you go through the CSV file rows. 您可以在浏览CSV文件行时求和。 (eg put the for class_ loop inside your rows loop) .. : (例如,将for class_循环放入行循环中)..:

>>> 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}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM