我有以下代码部分:
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')
'''
The name of the object doesn't have to be the name of the actual product, it can be the row number or whatever is easiest to use in this code. any help is very much appreciated :)
您需要某种用于存储对象的数据结构,列表似乎是个好主意,因此您可以简单地这样做:
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))
如果我正确理解了您想要的内容,则需要使用exec
进行动态评估:
for row in products:
exec("{0} = Product(row[0], row[1], row[2])".format(row[2]))
这将为您提供以每行最后一项命名的Product
。