'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)
Solution 1:[1]
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)
Solution 2:[2]
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.
Solution 3:[3]
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))
Solution 4:[4]
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])
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Smit Parmar |
| Solution 2 | Greg Hewgill |
| Solution 3 | Mohamed Yasser |
| Solution 4 |
