Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/315.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/wcf/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在一列中执行数学运算?_Python - Fatal编程技术网

Python 如何在一列中执行数学运算?

Python 如何在一列中执行数学运算?,python,Python,我有一个包含两行的文本文件,我需要使用Python从第1行的度量中减去第2行的度量。我知道我可以手动完成,但我的作业要求对其进行编码。理想情况下,我会打印这个值-我不需要将它附加到表中 行ID |名称|度量 1 |图书馆| 3627 2 |宿舍| 725 以下是我目前的代码: uDistFile = open("T:\\Students\\kheuser\\semprojclean\\udistance.txt","r") uBusStops = uDistFile.readlines()[1

我有一个包含两行的文本文件,我需要使用Python从第1行的度量中减去第2行的度量。我知道我可以手动完成,但我的作业要求对其进行编码。理想情况下,我会打印这个值-我不需要将它附加到表中

行ID |名称|度量
1 |图书馆| 3627
2 |宿舍| 725
以下是我目前的代码:

uDistFile = open("T:\\Students\\kheuser\\semprojclean\\udistance.txt","r")
uBusStops = uDistFile.readlines()[1:]

for stop in uBusStops:
    aList = stop.split(",")
    print "measures are", aList[2]

您的文件是所谓的DSV(缩写)格式。Python有一个名为
csv
的模块,可以读取其中的大多数样式。(它的第一个字母是“
c
”,因为传统上使用的分隔符是逗号。)

下面的代码使用它来执行您想要的操作(并将处理任意数量的行):

输出:

值:[3627725]
总数:4352
import csv

filename = "udistance.txt"
column = "Measure"

with open(filename, newline="") as uDistFile:
    reader = csv.DictReader(uDistFile, delimiter="|", skipinitialspace=True)
    values = [int(row[column]) for row in reader]

print('values:', values)
print('total:', sum(values))