Is there any way to change data type of each item of a list in Python?
I have a listof lists named listlog
with this structure:
[['2022-05-04 11:06:50', 'INFO', 'Database Connection', 'Database', '10.05', 'NULL'] [...]
Is there any way to change each item data type? The first one would be timestamp/datetime, the scond, third and fourth would be string, the fith would be float or numeric.
Is there any way? I've tested something like this, but didn't work
map(lambda item: Timestamp([item[0]]), listLog)
4 answers
-
answered 2022-05-04 10:20
Greg Hewgill
You should be able to do it with something like the following:
for item in listlog: item[0] = Timestamp(item[0]) item[4] = float(item[4])
Add an additional assignment for each data field that you need to convert.
-
answered 2022-05-04 10:33
Smit Parmar
You can try something like this.
from datetime import datetime for item in listdata: item[0]=datetime.strptime(item[0], '%Y-%M-%d %H:%m:%S') item[1]=str(item[1]) item[2]=str(item[2]) item[3]=str(item[3]) item[4]=float(item[4]) print(listt)
-
answered 2022-05-04 10:55
Mohamed Yasser
While I think Greg Hewgill's solution is the best practice, here is an answer using a map if you're interested in oneliners:
list(map(lambda item: [Timestamp(item[0])] + item[1:4] + [float(item[4])] + item[5:], listlog))
-
answered 2022-05-04 11:29
PUNEET PRIYADARSHI
for i in range(0,len(list_name)): # check condition of the item whether its a string or integer or date-time stamp then do typecasting.
for example :
if type(l[item])=int
and you want to convert it to string then write:l[item] = string(l[item])
How many English words
do you know?
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
how many words do you know
Powered by Examplum