person.CSV 文件如下所示:
Firstname,Surname,Birth Year,Hobby
John,Smith,1990,"tenis,piano"
Andrew,Josh,1988,"surfing,art"
我希望在程序爱好中将其表示为列表而不是字符串。我怎样才能强制到那个 DictReader?
我使用的python代码如下:
import csv
class Person(object):
extPerson = []
counter = 0
def __init__(self, **args):
for k, v in args.items():
setattr(self, k, v)
Person.counter += 1
Person.extPerson.append(self)
def __str__(self):
s=""
for k,v in self.__dict__.items():
s+=k+": "+v+", "
return s
csvdr = csv.DictReader(open('persons.csv'))
for p in csvdr:
print p
Person(**p)
for p in Person.extPerson:
print p
print p.Hobby
输出如下所示:
{'Birth Year': '1990', 'Hobby': 'tenis,piano', 'Surname': 'Smith', 'Firstname': 'John'}
{'Birth Year': '1988', 'Hobby': 'surfing,art', 'Surname': 'Josh', 'Firstname': 'Andrew'}
Birth Year: 1990, Hobby: tenis,piano, Surname: Smith, Firstname: John,
tenis,piano
Birth Year: 1988, Hobby: surfing,art, Surname: Josh, Firstname: Andrew,
surfing,art
我希望将构造函数中的爱好打包到列表中:
(...)
Birth Year: 1990, Hobby: ['tenis','piano'], Surname: Smith, Firstname: John,
['tenis', 'piano']
Birth Year: 1988, Hobby: ['surfing','art'], Surname: Josh, Firstname: Andrew,
['surfing', 'art']