1

I have a list of values, that can be string like "string" and can be numbers that are given in a string format as "2.3"

I want to convert strings of certain value to a number ("N/A"->-1) and to leave any other string untouched, moreover I need to convert the numbers that are given in a string, in the float format to string format ("1.0"->1) etc.

I managed to do so if I first run all over the list and convert the N/A values to -1 like so

for i in list:
    if i=="N/A": 
        i=-1

and then run with

l = [int(i) for i in l]

But I still might have strings, other then "N/A" and I don't want to have trouble trying to convert them, and need to use try in the second loop. how can I do that?

This is the code i try but i gives me syntax error

l = [try: int(float(i)) except: pass] for i in l

Origin list example: ["1.0","N/A","lol"] i need it to be [1,-1,"lol"]

5
  • Can you give example of your list before and how you want it to look after? Commented Mar 7, 2016 at 9:35
  • 1
    @Idos , i added an example Commented Mar 7, 2016 at 9:41
  • You can't change the iterating index inside a loop. Commented Mar 7, 2016 at 9:42
  • Possible duplicate of How can I handle exceptions in a list comprehension in Python? Commented Mar 7, 2016 at 10:11
  • @peter wood this is not a duplicate, this is another question, i don't do comparison here Commented Mar 7, 2016 at 10:31

4 Answers 4

3

With try except , try to cast to int if a exception occurs and if it's "N/A" so it should be replace by -1 :

li = ["1.0" , "N/A" , "12" , "2.0", "Ok"]

for i,v in enumerate(li):
    try:
        li[i] = int(float((v)))
    except:
        if(li[i] == "N/A"):
            li[i] = -1

li # [1, -1, 12, 2, "Ok"]
Sign up to request clarification or add additional context in comments.

2 Comments

i still need to keep strings that are not "NA" and i want to do it in the elegant one row loop if possible
You have another strings like "Ok" and dont want to convert them to -1?
2
def convert(value):
    if value == 'N/A':
        return -1
    try:
        return int(value)
    except ValueError:
        return value

Then:

[convert(value) for value in values]

Comments

0

You may encapsulate try-except statement in your own function and use it in list comprehension.

def try_int(s):
    try:
        return int(s)
    except ValueError:
        return s

l = [try_int(i) for i in l]

Comments

0

Do it in one loop.

l = ["N/A", "3", "5", "6"]

for idx,val in enumerate(l):
    try:
        l[idx] = int(val)
    except:
        l[idx] = -1

print l

Output

[-1, 3, 5, 6]

1 Comment

@captainshai it should but i think you should use Rogalski example cause its by far the best, here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.