【发布时间】:2016-05-15 02:17:26
【问题描述】:
我正在尝试编写一个 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]
【问题讨论】:
-
请记住,索引是从零开始的,因此对于
Fastener对象f,您的 3 个负载是f.load[0]、f.load[1]和f.load[2]。
标签: python class loops for-loop indexing