[英]Multiple data types in a python list
I have a list for birth data each record has 3 columns for [DOB, weight, height] as such:我有一个出生数据列表,每条记录都有 3 列 [出生日期、体重、身高],如下所示:
bd = [['10/03/2021 00:00','6.2', '33.3'],['12/04/2021 00:00','6.2', '33.3'],
['13/05/2021 00:00','6.2','33.3']]
I need to change the data types of this as they are all strings in the list I want the first item in the record to be datetime and then the rest to be floats.我需要更改它的数据类型,因为它们都是列表中的字符串,我希望记录中的第一项是日期时间,然后 rest 是浮点数。 I have:
我有:
newdata = [i[0] for i in bd]
p= []
for x in bd:
xy = datetime.datetime.strptime(x,'%d/%m/%Y %H:%M') # this works to change the data type
p.append(xy) #it fails to update this to the new list
I get an attribute error:我收到一个属性错误:
AttributeError: 'str' object has no attribute 'append'
I would like to achieve this just by utilizing pythons file IO operations.我想通过使用 pythons 文件 IO 操作来实现这一点。 I also want to maintain each record of data together in a list within the main list I just want to update the datatypes.
我还想将每条数据记录一起保存在主列表中的列表中,我只想更新数据类型。
Your code is incomplete, there may be unexpected variable coverage, you can try to use the list comprehension directly.你的代码不完整,可能有意想不到的变量覆盖,你可以尝试直接使用列表推导。
[[datetime.datetime.strptime(i[0],'%d/%m/%Y %H:%M'), float(i[1]), float(i[2])] for i in bd]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.