python 列表中的多种数据类型
Multiple data types in a python list
我有一个出生数据列表,每条记录有 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']]
我需要更改它的数据类型,因为它们都是列表中的字符串我希望记录中的第一项是日期时间,然后是浮点数。我有:
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
我收到一个属性错误:
AttributeError: 'str' object has no attribute 'append'
我想通过使用 pythons 文件 IO 操作来实现这个。我还想在主列表中的列表中将每条数据记录一起维护我只想更新数据类型。
你的代码不完整,可能会有意想不到的变量覆盖,你可以尝试直接使用列表推导
[[datetime.datetime.strptime(i[0],'%d/%m/%Y %H:%M'), float(i[1]), float(i[2])] for i in bd]
我有一个出生数据列表,每条记录有 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']]
我需要更改它的数据类型,因为它们都是列表中的字符串我希望记录中的第一项是日期时间,然后是浮点数。我有:
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
我收到一个属性错误:
AttributeError: 'str' object has no attribute 'append'
我想通过使用 pythons 文件 IO 操作来实现这个。我还想在主列表中的列表中将每条数据记录一起维护我只想更新数据类型。
你的代码不完整,可能会有意想不到的变量覆盖,你可以尝试直接使用列表推导
[[datetime.datetime.strptime(i[0],'%d/%m/%Y %H:%M'), float(i[1]), float(i[2])] for i in bd]