将元素列表分配为另一个列表中类实例的属性

0 投票
1 回答
26 浏览
提问于 2025-04-12 14:37

我用一个Excel表格里的数据来创建一个列表,然后想把这个列表里的数据展开,变成一个类实例的属性,使用*号来实现。

import openpyxl

class rowData: 
    def __init__(self, segment=None, country=None, product=None, discountBand=None, unitsSold=None, manufacturingPrice=None, salePrice=None, grossSales=None, discounts=None, sales=None, COGS=None, profit=None, date=None, monthNumber=None, monthName=None, year=None):
        self.segment            = segment
        self.country            = country
        self.product            = product
        self.discountBand       = discountBand
        self.unitsSold          = unitsSold
        self.manufacturingPrice = manufacturingPrice
        self.salePrice          = salePrice
        self.grossSales         = grossSales
        self.discounts          = discounts
        self.sales              = sales
        self.COGS               = COGS
        self.profit             = profit
        self.date               = date
        self.monthNumber        = monthNumber
        self.monthName          = monthName
        self.year               = year

我有一个包含10个类实例的列表,还有一个函数可以从Excel表格的第i行提取数据,生成一个列表:

properList = []
for i in range(10):
    properList.append(rowData(i))

def createListforRow(i):
    newList = []
    for cell in sheet[i]:
        convertToString = str(cell.value)
        newList.append(convertToString)
    return newList

我已经成功地把testList展开成一个单独的类实例exampleClassInstance的属性。

testList = createListforRow(2)
exampleClassInstance = rowData(*testList)

但是,当我尝试直接把数据展开到properList里的类实例时,遇到了一些问题,比如:

testList = createListforRow(2)
properList[0] = (*testList)

我得到的结果是:

    properList[0] = (*testList)
                     ^^^^^^^^^
SyntaxError: cannot use starred expression here

理想情况下,我希望能多次调用createListforRow,并把生成的列表赋值给properList中任意一个rowData类实例的属性。

我使用的数据如下:

微软财务样本

1 个回答

0

星号(*)这个符号用来一次性传递多个参数给构造函数,就像你在例子中实例化一个类那样。你不能像你代码里那样构建一个列表。你可以这样做:

properList = list(testList)

如果你想要一个列表的副本。不过我建议你不要为这个创建一个类。可以直接使用一个 命名元组(named_tuple)

撰写回答