我正在尝试编写一个Python脚本,它将读取通过CSV文件输入的一系列加载,并返回生成的力向量。CSV的格式为:
x,y,z,load_in_x,load_in_y,load_in_z
u,v,w,load_in_x,load_in_y,load_in_z
...
脚本如下:
^{pr2}$当我运行它时,我总是得到以下错误:
Traceback (most recent call last):
File "bolt_group.py", line 49, in <module>
print(sumLin(F))
File "bolt_group.py", line 42, in sumLin
xSum += fastenerList[i].load[1]
TypeError: list indices must be integers, not Fastener
我尝试过将循环索引i
更改为int(i)
,但仍然会给我带来问题。如果我像下面这样手动添加它们就没有问题了。在
xSum = F[1].load[1] + F[2].load[1] + F[3].load[1]
可以对代码进行各种改进。正如jochen所说,直接迭代列表比使用索引更像python。该原则也可以应用于填充紧固件对象列表的代码。在
但是,我们可以使用内置的
^{pr2}$zip
函数进一步压缩sumLin
函数:显然,我的代码没有经过测试,因为你没有给我们提供任何样本数据。。。在
^{pr2}$i
是Fastener
对象,不是整数。因此,调用fastenerList[i]
是无效的;您应该传入一个整数。更改:到
我认为一种更具python风格的方法是迭代紧固件列表:
如果您希望您的代码非常快,可以将csv数据加载到努比·恩达雷让numpy进行求和(避免python中的多个for循环),但是如果速度不是那么重要的话,您可以使用这种方法。在
相关问题 更多 >
编程相关推荐