2

我有以下代码部分:

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)

如图所示,共有三列,代码末尾分别是:高度、半径、名称。我需要能够将我创建的数组的每一行更改为以后可以在代码中使用的对象。我在代码开头导入了 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')

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

4

2 回答 2

2

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

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

这会产生一个供以后使用的产品列表

于 2019-11-27T18:19:29.513 回答
0

您可以使用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))
于 2019-11-27T18:29:34.540 回答