【问题标题】:Adding numbers in a csv file Python code在 csv 文件 Python 代码中添加数字
【发布时间】:2018-08-01 01:05:08
【问题描述】:
我的 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 代码是这样的
Honda:79734397
Toyota:2343434 . (the numbers are for demonstration and not exact)
最后我如何将所有汽车的所有里程加起来?
【问题讨论】:
标签:
python
csv
dictionary
sum
key
【解决方案1】:
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
【解决方案2】:
这应该会有所帮助。遍历数据并使用字典,其中键是汽车型号,值的总和是值。
演示:(我使用字符串只是为了展示逻辑)
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
输出:
{'Nissan': 1989, 'Honda': 49341, 'Toyota': 541996, 'Ford': 40020, 'Bmw': 354839, 'Lexus': 8141}
【解决方案3】:
将csv文件读入二维数组或列表,制作python dict,并将数组中每个数组的第一个元素设置为字典键(本例中为汽车名称),其余元素为数组中的每个 aray 将其解析为 int 并调用 sum 函数。将其添加到 dict 的值中。
【解决方案4】:
你可以试试这个:
import csv
with open('filename.csv') as f:
final_data = [[a, sum(map(int, b))] for a, *b in csv.reader(f)]