从数组的每一行生成一个对象

2024-04-18 21:05:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下代码部分:

class Product(Cylinder): ### Creates a child class of Cylinder called Product
        def __init__(self, height, radius, name): ### new class paramenter, we now have name
            super().__init__(height, radius) ### inherits the previous initial viables, no need to rewrite.
            self.name = name ### name is now a new parameter.

        def objectName(self): ### new functions to return the name of the object
            return self.name

#### The bit about csv spreadsheets
import csv ### imports the csv module
with open('shopping.csv') as csv_file: ### opens the csv file
    reader = csv.reader(csv_file) ### defines the variable containing the information
    next(csv_file) ### goes to the next line, ignoring the title
    products = ["name","radius","hieght"] ### create's a base array for the information to be written to
    for row in reader: ### for each row
        products = np.vstack((products,row)); ### writes each row of the imported file to the array

    products = np.delete(products, (0), axis=0) ### removes the non-useful information (row 0)
    products[:,[0, 2]] = products[:,[2, 0]] ### switches first and third row to match our class and function inputs
    print(products)

如图所示,代码末尾有三列:height、radius、name。我需要能够将我创建的数组中的每一行更改为对象,以便稍后在代码中使用。我在代码的开头导入了numpy。如果可能的话,我想避免导入任何额外的模块。你知道吗

打印时数组的内容:

[['30.0' '4.0' 'Pringles ']
 ['12.2' '3.3' 'Coke can']
 ['7.5' '4.1' "Cadbury's Hot Chocolate"]
 ['8.2' '3.2' 'Green Giant Sweetcorn']
 ['8.8' '11.8' 'Celebrations Tub']
 ['15.0' '0.8' 'Rowntrees Fruit Pastilles']
 ['13.0' '6.0' 'M&S Best Ginger Nuts Tub']
 ['17.0' '3.3' 'Monster Energy Drink']
 ['10.9' '3.8' 'Heinz Baked Beans']]

我需要一种方法使每一行都成为一个对象,例如:

pringles = Product(30.0,4.0,'Pringles')
cokeCan = Product(12.2,3.3,'Coke Can')

对象的名称不必是实际产品的名称,它可以是行号或任何在代码中最容易使用的名称。非常感谢您的帮助:)


Tags: ofcsvtheto代码nameselfnew
2条回答

您需要某种数据结构来存储对象,也许列表似乎是个好主意,因此您可以简单地执行以下操作:

list_of_products = [Product(h, r, n) for (h, r, n) in original_array]

这将生成供以后使用的产品列表

可以使用itertools.starmap将元组序列作为参数映射到Product的构造函数:

from itertools import starmap
with open('shopping.csv') as csv_file:
    reader = csv.reader(csv_file)
    next(reader)
    products = list(starmap(Product, reader))

相关问题 更多 >