thebeancounter
thebeancounter

Reputation: 4839

Using "try" for a list loop operation

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"]

Upvotes: 1

Views: 1001

Answers (4)

Kordi
Kordi

Reputation: 2465

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]

Upvotes: 0

ᴀʀᴍᴀɴ
ᴀʀᴍᴀɴ

Reputation: 4528

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"]

Upvotes: 3

Łukasz Rogalski
Łukasz Rogalski

Reputation: 23203

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]

Upvotes: 0

Open AI - Opting Out
Open AI - Opting Out

Reputation: 24133

def convert(value):
    if value == 'N/A':
        return -1
    try:
        return int(value)
    except ValueError:
        return value

Then:

[convert(value) for value in values]

Upvotes: 2

Related Questions