【问题标题】:Multiple data types in a python listpython列表中的多种数据类型
【发布时间】:2021-06-16 11:35:18
【问题描述】:

我有一个出生数据列表,每条记录都有 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 操作来实现这一点。我还想将每条数据记录一起保存在主列表中的列表中,我只想更新数据类型。

【问题讨论】:

    标签: python list datetime types floating-point


    【解决方案1】:

    你的代码不完整,可能有意外的变量覆盖,你可以尝试直接使用列表推导。

    [[datetime.datetime.strptime(i[0],'%d/%m/%Y %H:%M'), float(i[1]), float(i[2])] for i in bd]
    

    【讨论】:

      猜你喜欢
      • 2020-02-16
      • 2011-05-19
      • 1970-01-01
      • 2021-12-27
      • 2013-11-06
      • 1970-01-01
      • 2012-10-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多