Reputation: 2193
So I have a list of string a = ['1', '2', '']
or a = ['1', '2', 'NAN']
, and I want to convert it to [1, 2, 0]
or [1, 2, -1]
(namely NAN
to -1
); I used
a = [int(ele) for ele in a]
, but got an error
ValueError: invalid literal for int() with base 10: ''
So the empty string cannot be converted automatically. Of course I could explicitly loop through the list ,but I wonder if there are more elegant/compact/efficient way.
Upvotes: 1
Views: 120
Reputation: 103
def convert(myList):
newList = [0]*len(myList)
for i in range(len(myList)):
try:
newList[i] = int(myList[i])
except:
newList[i] = -1
return newList
obviously this try/except just puts -1 for anything that can't be converted to an integer
easily converted to a more specific if myList[i]=='NAN': newList[i]=-1
Upvotes: 0
Reputation: 19030
Try something like this:
>> a = ['1', '2', '']
>>> def toint(s, default=0):
... try:
... return int(s)
... except ValueError:
... return default
...
>>> [toint(x) for x in a]
[1, 2, 0]
>>>
This has the added benefit of conforming to Python's Duck Typing idiom and giving you the flexibility to change the default if processing your data results in a ValueError
exception. e.g:
>>> [toint(x, None) for x in a]
[1, 2, None]
Upvotes: 3
Reputation:
>>> a = ['1', '2', 'NAN', '']
>>>
>>> def to_int(value):
... try:
... return int(value)
... except ValueError:
... if value == 'NAN':
... return -1
... return 0
...
>>> [to_int(x) for x in a]
[1, 2, -1, 0]
>>>
Upvotes: 0
Reputation: 625
>>> a = ['1', '2', '', 'NAN']
>>> listofInt = map(lambda s: int(s) if s not in 'NAN' else -1 if s == 'NAN' else 0, a)
>>> print listofInt
>>> [1, 2, 0, -1]
You could write a lambda function even as a anonymous function.
Upvotes: 0
Reputation: 12092
Modifying your list comprehension a little as:
a = [int(ele) if ele else 0 for ele in a]
gives what you want. This will work if the non number is a '' not if it is a NAN. If 'NAN' is part of the list, this will do it:
a = [int(ele) if ele != 'NAN' else 0 for ele in a]
Upvotes: 0
Reputation: 304137
Use a dict
to handle your unusual values
a = [int({'NAN': '-1', '': 0}.get(i, i)) for i in a]
Upvotes: 0
Reputation: 18898
You could just write a function that makes use of int
and then have a fallback condition on failures that does what you want for a input string, then call that function in the list comprehension statement.
example:
def converter(ele):
# result = your integer conversion logic
return result
a = [converter(ele) for ele in elements]
Upvotes: 1