Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to generate a list comprehension with a conditional where the conditional is a NameError

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[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

>Solution :

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]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading