Suppose the following list:
l = ['1','2','M']
How can I transform l
to l_1
via a list comprehension?
l_1 = [1, 2, 'M']
I attempted the below without success.
[eval(c) if eval(c) not NameError else c for c in l]
File "<ipython-input-241-7c3f63ffe51b>", line 1
[eval(c) if c not NameError else c for c in list(a)]
^
SyntaxError: invalid syntax
CodePudding user response:
Hi,
You could validate each element of the list l as strings, even if you already have some digits on it such as l = ['1','2','M',3,'p'], that way you have that validation there by passing them all to string and then verifying if the element is digit, and if so, you pass it to int, of float, or number to the new l_1 and if it is not, you simply pass it as string. In this case I will convert each numeric element to int, but you could choose to pass it to number in any other type such as float, for example, if the list contains floating elements.
l = ['1','2','M',3,'p']
l_1 = [int(el) if str(el).isdigit() else el for el in l]
print(l_1)
I certainly hope this helps, good luck and keep coding, it's always fun!
CodePudding user response:
Assuming your general case looks like this, you could use isdigit to only convert numbers.
l=['1','2','M']
l1=[int(c) if c.isdigit() else c for c in l]