我正在尝试编写一个 Python 程序来浏览两个列表x[ ]
和y[ ]
。列表中的元素是从文件中读取的。每个x[ ]
元素都有一个相应的y[ ]
元素。 x[ ]
和 y[ ]
在图形上相互绘制(已绘制,但由于此代码不需要绘制,因此删除了绘图)。
我想在x[ ]
上集成图形并创建另一个列表cumulative[ ]
。我试图让cumulative[ ]
的第 n 个元素保持第一个x[ ]
元素和第 n 个x[ ]
元素之间的积分值。
在附加cumulative[ ]
之前,我尝试声明引用第 i 个x[ ]
、y[ ]
个元素和第 i-1 个元素的变量。这是出现以下错误消息的位置:
Traceback (most recent call last):
File "C:/Python27/andy_experiments/cumulate1", line 39, in <module>
xprevious = x[i - 1]
TypeError: unsupported operand type(s) for -: 'tuple' and 'int' "
我已经查看了其他人的工作 Python 代码来访问列表中的上一个/下一个值,但我无法弄清楚为什么我的代码无法做到这一点。
我的代码:
import matplotlib.pyplot as plt
x = []
y = []
cumulative = []
readFile = open('data_03.txt', 'r')
sepFile = readFile.read().split('n')
readFile.close()
count = 0
# The code was originally used to plot data, hence "plotPair" (line in the file)
for plotPair in sepFile:
if plotPair.startswith("!"):
continue
if plotPair.startswith(" !"):
continue
if plotPair.startswith("READ"):
continue
if plotPair.startswith("NO"):
continue
if plotPair == "n":
continue
if not plotPair.strip():
continue
else:
xAndY = plotPair.split(' ')
x.append(float(xAndY[0]))
y.append(float(xAndY[3]))
for i in enumerate(zip(x, y)):
count = count + 1
if count < 2:
continue
else:
xprevious = x[i - 1] # this is line 41, where the (first) error lies
xnow = [i]
yprevious = y[i - 1]
ynow = y[i]
cumulative.append((xnow - xprevious)*(ynow - yprevious))
enumerate()
生成一个元组序列;索引和包装的可迭代对象中的元素。您正在尝试使用该元组;对于zip(x, y)
序列,这意味着你得到一个带有 (0, (x[0], y[0]))
的序列,然后是 (1, (x[1], y[1]))
等。
将元组解压缩到索引和x, y
对中:
for i, (xval, yval) in enumerate(zip(x, y)):
if i > 0:
xprevious = x[i - 1]
yprevious = y[i - 1]
cumulative.append((xval - xprevious) * (yval - yprevious))
我也用i
测试代替了count < 2
测试。
您只需通过分配即可更轻松地跟踪前一对:
previous = None
for xval, yval in zip(x, y):
if previous:
xprevious, yprevious = previous
cumulative.append((xval - xprevious) * (yval - yprevious))
previous = xval, yval
您需要解压缩enumerate
返回的元组,这些元组将被(index, value)
。例如:
>>> x = [1,2,3,4]
>>> y = [2,4,6,8]
for index, pair in enumerate(zip(x,y)):
print(index)
0
1
2
3
您当前的索引使用这些元组作为索引,这就是错误告诉您的
for i in enumerate(zip(x,y)):
print(i)
(0, (1, 2))
(1, (2, 4))
(2, (3, 6))
(3, (4, 8))
修复代码的最快更改是将for
循环更改为
for i, pair in enumerate(zip(x, y)):