将列表项转换为定义的数据类型 [英] Convert list items to defined data type

查看:163
本文介绍了将列表项转换为定义的数据类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是python的新手,我不确定如何执行以下操作.

I'm rather new to python and I'm not sure how to do the following.

我有一个列表foo,其中包含某个图的元数据和测量值.例如,plotID,测量日期,测量员的姓名缩写,几个测量值和一个分类变量.

I have a list foo containing metadata and measurement values for a certain plot. For example, a plotID, survey date, initials of surveyors, several measurement values and a categorical variable.

foo= ['plot001', '01-01-2013', 'XX', '10', '12.5', '0.65', 'A']

因为这些数据是从.txt中读取的,所以所有列表项都是字符串.我的问题是:如何将每个列表项转换为适当的数据类型?.我可以列出所需的数据类型:

Because these data are read from a .txt, all list items are strings. My question is: how do I convert each list item to the approporiate datatype?. I can make a list with the desired data types:

dType= ['str', 'str', 'str', 'int', 'float', 'float', 'float', 'str']

如果我可以将dType中的每个项目作为函数应用于foo中的匹配元素,将是很好的:

It would be nice if I could apply each item in dType as function to the matching element in foo as such:

out= [str(foo[0]), str(foo[1]), str(foo[2]), int(foo[3]), float(foo[4]), float(foo[5]), float(foo[6]), str(foo[7])]

但是我确定必须有一个更好的解决方案!感谢您的任何建议!

but I'm sure there must be a better solution! Thanks for any suggestions!

推荐答案

使dType成为内置工厂列表,而不是字符串列表:

Instead of a list of strings, make dType a list of builtin factories:

dType= [str, str, str, int, float, float, str]

(您删除了另外一个float)

然后只需使用zip:

[t(x) for t,x in zip(dType,foo)]
Out[6]: ['plot001', '01-01-2013', 'XX', 10, 12.5, 0.65, 'A']

奖金:您甚至可以幻想并创建自己的工厂功能,并使用与functools.partial相同的方式来应用它们.说,如果您希望该日期变成一个datetime对象:

Bonus: you could even get fancy and make your own factory functions and apply them in the same manner with functools.partial. Say, if you wanted that date to turn into a datetime object:

def datetime_factory(format,s):
    from datetime import datetime
    return datetime.strptime(s,format)

from functools import partial

dType= [str, partial(datetime_factory,'%d-%m-%Y'), str, int, float, float, str]

[t(x) for t,x in zip(dType,foo)]
Out[29]: ['plot001', datetime.datetime(2013, 1, 1, 0, 0), 'XX', 10, 12.5, 0.65, 'A']

(这里需要创建自己的工厂def,因为partial仅允许您部分应用最左侧参数,而strptime要求首先设置要格式化的字符串)

(making our own factory def was needed here since partial only allows you to partially apply the leftmost arguments, and strptime requires the string-to-be-formatted first)

这篇关于将列表项转换为定义的数据类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆