【问题标题】:Making an object from each row of an array从数组的每一行创建一个对象
【发布时间】:2020-03-23 08:37:20
【问题描述】:

我有以下代码部分:

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')

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

【问题讨论】:

  • 您可以将每组列设为字典,然后将每个部分分别附加到您的对象列表中。
  • 看来你让事情变得相当复杂。你能发布一个你开始使用的 csv 数据的例子吗?

标签: python list class object


【解决方案1】:

您需要某种数据结构来存储您的对象,列表似乎是个好主意,所以您可以简单地这样做:

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

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

【讨论】:

  • 对不起,因为我对 Python 还比较陌生,我需要使用对象列表来创建另一个列表,其中包含对象的函数。例如,我的函数之一是“objectname”.volume()。我将如何使用此列表来实现这一目标?澄清一下,我已经在对象类中定义了函数。
  • 你可以简单地做类似for product in list_of_products: product.function()
【解决方案2】:

您可以使用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))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-12
    • 2021-03-30
    • 2021-12-24
    • 1970-01-01
    • 2020-12-21
    • 1970-01-01
    • 2018-08-20
    • 2021-07-20
    相关资源
    最近更新 更多