在类实例列表中循环

2024-09-30 01:25:59 发布

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

我正在尝试编写一个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]

Tags: 文件csvinpy脚本格式linegroup
3条回答

可以对代码进行各种改进。正如jochen所说,直接迭代列表比使用索引更像python。该原则也可以应用于填充紧固件对象列表的代码。在

with open(path,"r") as inputFile:
    # Create a list of Fastener objects from each line in the mapping file
    F = []
    for line in inputLines:
        data = [float(i) for i in line.strip().split(",")]
        location = data[:3]
        load = data[3:]
        F.append(Fastener(location, load))

# Function to sum all fastener loads and return the resulting linear force
# vector
def sumLin(fastenerList):
    xSum = 0
    ySum = 0
    zSum = 0
    for fastener in fastenerList:
        xSum += fastener.load[0]
        ySum += fastener.load[1]
        zSum += fastener.load[2]
    linVector = [xSum, ySum, zSum]
    return linVector

但是,我们可以使用内置的zip函数进一步压缩sumLin函数:

^{pr2}$

显然,我的代码没有经过测试,因为你没有给我们提供任何样本数据。。。在

fastenerList[i].load[1]

iFastener对象,不是整数。因此,调用fastenerList[i]是无效的;您应该传入一个整数。更改:

^{pr2}$

for i in range(len(fastenerList)): # 'i' is an integer 

我认为一种更具python风格的方法是迭代紧固件列表:

for fastener in fastenerList:
    xSum += fastener.load[0]
    ySum += fastener.load[1]
    zSum += fastener.load[2]

如果您希望您的代码非常快,可以将csv数据加载到努比·恩达雷让numpy进行求和(避免python中的多个for循环),但是如果速度不是那么重要的话,您可以使用这种方法。在

相关问题 更多 >

    热门问题