Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/git/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在类实例列表中循环_Python_Class_Loops_For Loop_Indexing - Fatal编程技术网

Python 在类实例列表中循环

Python 在类实例列表中循环,python,class,loops,for-loop,indexing,Python,Class,Loops,For Loop,Indexing,我正在尝试编写一个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 coll

我正在尝试编写一个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
紧固件
对象,而不是整数。因此调用
fastenerList[i]
是无效的;您应该传入一个整数。更改:

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


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

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

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

可以对代码进行各种改进。正如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
函数:

def sumLin(fastenerList):
    loads = [fastener.load for fastener in fastenerList]
    return [sum(t) for t in zip(*loads)]

显然,我的代码未经测试,因为您没有向我们提供任何样本数据…

记住,索引是零基的,因此对于
紧固件
object
f
而言,您的3个载荷分别是
f.load[0]
f.load[1]
f.load[2]
for fastener in fastenerList:
    xSum += fastener.load[0]
    ySum += fastener.load[1]
    zSum += fastener.load[2]
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
def sumLin(fastenerList):
    loads = [fastener.load for fastener in fastenerList]
    return [sum(t) for t in zip(*loads)]