假设我有一个数据集('test.csv'),如下所示:
Name,Fruit,Price
John,Apple,1.00
Steve,Apple,1.00
John,Mango,2.00
Adam,Apple,1.00
Steve,Banana,1.00
尽管有几种更简单的方法可以做到这一点,但我还是希望将这些信息组织为python中的一个类。因此,理想情况下,类的实例如下所示:
{'name': 'John', 'Fruits': ['Apple','Mango'], 'Price':[1.00, 2.00]}
我将数据集加载到类中的方法是将每个实例存储在列表中。
class org(object):
def __init__(self,name,fruit,price):
self.name = name
self.fruit = [fruit]
self.price = [price]
classes = []
with open('test.csv') as f:
for line in f:
if not 'Name' in line:
linesp=line.rstrip().split(',')
name = linesp[0]
fruit = linesp[1]
price = linesp[2]
inst = org(name,fruit,price)
classes.append(inst)
for c in classes:
print (c.__dict__)
在这种情况下,我怎么知道'John'是否已经存在作为实例?
如果是这样,我该如何更新“约翰”?有课法吗?
@classmethod
def update(cls, value):
cls.fruit.append(fruit)
最佳答案
无需任何特殊更新实例。您班级的属性是公开的,因此只需访问它们即可进行更新。
如果您坚持使用列表作为实例容器,则可以做某事。像这样:
classes = []
with open('test.csv') as f:
for line in f:
if not 'Name' in line:
name,fruit,price=line.rstrip().split(',')
exists = [inst for inst in classes if inst.name == name]
if exists:
exists[0].fruit.append(fruit)
exists[0].price.append(price)
else:
classes.append(org(name,fruit,price))
for c in classes:
print (c.__dict__)
但是,我建议改用dict,因为它使查找和访问实例更加容易
classes = {}
with open('test.csv') as f:
for line in f:
if not 'Name' in line:
name,fruit,price=line.rstrip().split(',')
if name in classes:
classes.get(name).fruit.append(fruit)
classes.get(name).price.append(price)
else:
classes.update({name: org(name,fruit,price)})
for c in classes.values():
print (c.__dict__)
两种解决方案都可以给您带来相同的效果:
{'name': 'John', 'fruit': ['Apple', 'Mango'], 'price': ['1.00', '2.00']}
{'name': 'Steve', 'fruit': ['Apple', 'Banana'], 'price': ['1.00', '1.00']}
{'name': 'Adam', 'fruit': ['Apple'], 'price': ['1.00']}
为了完整起见,下面注释中的@MadPhysicist可能是通过笨拙的方式更新dict的意思是,我使用dict的方法而不是通过订阅访问项目。
# update existing instance in the dict
classes[name].fruit.append(fruit)
# add new instance to the dict
classes[name] = org(name, fruit, price)
我个人只是觉得有些难看,因此我倾向于使用这些方法:)