In Python, I want to convert a list of strings:
l = ['sam','1','dad','21']
and convert the integers to integer types like this:
t = ['sam',1,'dad',21]
I tried:
t = [map(int, x) for x in l]
but is showing an error.
How could I convert all intable strings in a list to int, leaving other elements as strings?
My list might be multi-dimensional. A method which works for a generic list would be preferable:
l=[['aa','2'],['bb','3']]
[map(int, x) for x in l]will try to turn each string into a list of integers, character by character. You probably meant eithermap(int, l)or[int(x) for x in l].[int(x) for x in l]will throwValueErrors for non-numeric strings.map(lambda line: [int(i) if i.isdigit() else i for i in line.split(",")])- note this does not account for negative integers.