3 回答
TA贡献1712条经验 获得超3个赞
你可以有:
types = (str, str, int, int, int, float, float, float, float)
然后改变你的:
data= [tuple(line.split(',')) for line in lines[1:]]
到:
data = [tuple([t(val) for t, val in zip(types, line.split(','))])
for line in lines[1:]]
尝试使用这些行(在标题行之后):
Boston,MA,20489,19715,23610,9.9,401,15.6,4499.63
Trenton,NJ,26835,26573,25113,9.9,345,23,552.13
给出该值data:
[('Boston', 'MA', 20489, 19715, 23610, 9.9, 401.0, 15.6, 4499.63),
('Trenton', 'NJ', 26835, 26573, 25113, 9.9, 345.0, 23.0, 552.13)]
TA贡献1828条经验 获得超3个赞
另一个解决方案:
data = [ ('Boston', 'MA', '20489', '19715', '23610', '9.9', '401', '15.6', '4499.63'),
('Trenton', 'NJ', '26835', '26573', '25113', '9.9', '345', '23', '552.13') ]
new_t = [(*t[:2], *map(int, t[2:5]), *map(float, t[5:9])) for t in data]
print(new_t)
印刷:
[('Boston', 'MA', 20489, 19715, 23610, 9.9, 401.0, 15.6, 4499.63),
('Trenton', 'NJ', 26835, 26573, 25113, 9.9, 345.0, 23.0, 552.13)]
添加回答
举报