在csv文件Python cod中添加数字

2024-05-23 15:23:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我的csv文件如下所示:

Honda   100 90  345 3453    45353 
Toyota  453 656 909 5435    534543 
Nissan  123 32  535 345     954   
Ford    543 54  345 34543   4535 
Lexus   345 545 345 3453    3453  
Bmw     345 343 353 345     353453

我怎样把每行的总英里数加起来,然后把它连接到车的钥匙上。在

所以从CSV开始,我希望我的python代码是这样的

^{pr2}$

最后,我怎么把从这辆车跑的里程加起来?在


Tags: 文件csv代码钥匙里程fordlexusnissan
3条回答

这应该有帮助。迭代数据并使用字典,其中key是car model,值的总和是value。在

演示:(我使用字符串只是为了显示逻辑)

s = """Honda 100 90 345 3453 45353 
 Toyota 453 656 909 5435 534543 
 Nissan 123 32 535 345 954 
 Ford 543 54 345 34543 4535 
 Lexus 345 545 345 3453 3453 
 Bmw 345 343 353 345 353453"""

d = {} 
for i in s.split("\n"):
    val = i.strip().split()
    if val[0] not in d:
        d[val[0]] = sum(map(int, val[1:]))    #map function to convert string to int

print d

输出:

^{pr2}$
import csv
total=[]
with open('some.csv', newline='') as csvfile:
  spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|')
  for row in spamreader:
    print(row[0],end=' ')
    total.append(sum(list(map(int,list(filter(None, row[1:]))))))
    print(sum(list(map(int,list(filter(None, row[1:]))))))
  print('Total: ',sum(total))

使用上述代码

使用此链接检查输出

https://repl.it/repls/ForcefulForcefulEfficiency

将csv文件读入2D数组或列表,生成python dict,并将数组中每个数组的第一个元素设置为dictionary键(本例中为car name),对于数组中每个aray的其余元素,将其解析为int并调用sum函数。把它加到dict的值上

相关问题 更多 >