gpt4 book ai didi

python - 循环遍历类实例列表

转载 作者:太空宇宙 更新时间:2023-11-03 12:57:28 25 4
gpt4 key购买 nike

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

这是脚本:

# Fastener class containing an ID, location in space, and load vector
class Fastener(object):
"""A collection of fasteners"""
noOfFstnrs = 0
def __init__(self,xyz,load):
self.xyz = xyz
self.load = load
Fastener.noOfFstnrs += 1
self.fastID = Fastener.noOfFstnrs

def __repr__(self):
return """Fastener ID: %s
Location: %s
Load: %s""" % (self.fastID, self.xyz, self.load)


# Request the mapping CSV file from the user. The format should be:
# x,y,z,load_in_x,load_in_y,load_in_z
path = input("Fastener mapping file: ")

with open(path,"r") as inputFile:
inputLines = inputFile.readlines()

# Create a list of Fastener objects from each line in the mapping file
F = []
for line in range(len(inputLines)):
inputLines[line] = inputLines[line].strip('\n')
inputLines[line] = inputLines[line].split(",")
location = [float(i) for i in inputLines[line][:3]]
load = [float(i) for i in inputLines[line][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 i in fastenerList:
xSum += fastenerList[i].load[1]
ySum += fastenerList[i].load[2]
zSum += fastenerList[i].load[3]
linVector = [xSum, ySum, zSum]
return linVector

# Print
print(sumLin(F))

当我运行它时,我不断收到以下错误:

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]

最佳答案

fastenerList[i].load[1]

i 是一个 Fastener 对象,不是整数。所以调用fastenerList[i]是无效的;你应该传递一个整数。变化:

for i in fastenerList: # 'i' is a 'Fastener' object

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

关于python - 循环遍历类实例列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35218478/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com