本文介绍了列出对类对象的理解的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在subfile.py中有一个名为StrucData的类

I have a class named StrucData in subfile.py

class StrucData:
def __init__(self, name):
    self.name=name

def loadData(self, size=1, cost=1):
    self.size=size
    self.cost=cost

在主文件中我:

  1. 调用子文件,
  2. 创建数据名称列表
  3. 在列表中循环以实例化对象;和
  4. 使用"loadData"方法为每个对象加载数据(为了使本示例易于使用,我使用相同的大小"和成本".)

从子文件导入StrucData中的

    from subfile import StrucData

    listIndex=['data1','data2','data3']

    # Create a list of objects
    listObjects=[]

    # Iterate through the list of objects
    for i in range(3):
        data=StrucData(listIndex[i])
        data.loadData(size=3, cost=4)
        listObjects.append(data)

我想做的就是使用列表理解来做同样的事情

What I am trying to do is doing the same thing using list comprehension, to obtain

listObjects=[object1, object2, object3]

我已经尝试过类似的

listObjects=[[StrucData(listIndex[i]) for k in range(3)] listObjects[i].loadData(size=3, cost=4) for i in range(3)]]

这当然是行不通的,但是我不知道该怎么做.

which doesn't work of course, but I don't know how to do it properly.

请问我对代码的建议,以便使用列表理解来获得所需的输出?

Could I please have advice on my code to obtain the desired outputs using a list comprehension??

推荐答案

如果您可以随意在 StrucData.loadData()的最后一行附加 return self subfile.py ,可以这样简化:

If you are free to append return self to the last line of StrucData.loadData() within subfile.py, it could be simplified like this:

# in the main file
listObjects = [StrucData(idx).loadData(size=3, cost=4) for idx in listIndex]

否则,您必须单独执行此操作,因为 loadData()不会为列表理解表达式返回任何内容.

Otherwise, you have to do this separately because loadData() won't return anything for a list comprehension expression.

listObjects = [StrucData(idx) for idx in listIndex]
for i in range(3):
    listObjects[i].loadData(size=3, cost=4)

这篇关于列出对类对象的理解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 19:37