Skip to content
Advertisement

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:

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. 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. I also want to maintain each record of data together in a list within the main list I just want to update the datatypes.

Advertisement

Answer

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]
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement