Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert list of intable strings to int

In Python, I want to convert a list of strings:

l = ['sam','1','dad','21']

and convert the integers to integer types like this:

t = ['sam',1,'dad',21]

I tried:

t = [map(int, x) for x in l]

but is showing an error.

How could I convert all intable strings in a list to int, leaving other elements as strings?

My list might be multi-dimensional. A method which works for a generic list would be preferable:

l=[['aa','2'],['bb','3']]

like image 651
sum2000 Avatar asked Mar 26 '12 09:03

sum2000


4 Answers

I'd use a custom function:

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

Example:

>>> [try_int(x) for x in  ['sam', '1', 'dad', '21']]
['sam', 1, 'dad', 21]

Edit: If you need to apply the above to a list of lists, why didn't you converted those strings to int while building the nested list?

Anyway, if you need to, it's just a matter of choice on how to iterate over such nested list and apply the method above.

One way for doing that, might be:

>>> list_of_lists = [['aa', '2'], ['bb', '3']]
>>> [[try_int(x) for x in lst] for lst in list_of_lists]
[['aa', 2], ['bb', 3]]

You can obviusly reassign that to list_of_lists:

>>> list_of_lists = [[try_int(x) for x in lst] for lst in list_of_lists]
like image 72
Rik Poggi Avatar answered Nov 03 '22 06:11

Rik Poggi


I would create a generator to do it:

def intify(lst):
    for i in lst:
        try:
            i = int(i)
        except ValueError:
            pass
        yield i

lst = ['sam','1','dad','21']
intified_list = list(intify(lst))
# or if you want to modify an existing list
# lst[:] = intify(lst)

If you want this to work on a list of lists, just:

new_list_of_lists = map(list, map(intify, list_of_lists))
like image 29
agf Avatar answered Nov 03 '22 06:11

agf


How about using map and lambda

>>> map(lambda x:int(x) if x.isdigit() else x,['sam','1','dad','21'])
['sam', 1, 'dad', 21]

or with List comprehension

>>> [int(x) if x.isdigit() else x for x in ['sam','1','dad','21']]
['sam', 1, 'dad', 21]
>>> 

As mentioned in the comment, as isdigit may not capture negative numbers, here is a refined condition to handle it notable a string is a number if its alphanumeric and not a alphabet :-)

>>> [int(x) if x.isalnum() and not x.isalpha() else x for x in ['sam','1','dad','21']]
['sam', 1, 'dad', 21]
like image 40
Abhijit Avatar answered Nov 03 '22 05:11

Abhijit


For multidimenson lists, use recursive technique may help.

from collections import Iterable
def intify(maybeLst):
    try:
        return int(maybeLst)
    except:
        if isinstance(maybeLst, Iterable) and not isinstance(lst, str):
            return [intify(i) for i in maybeLst] # here we call intify itself!
        else:
            return maybeLst

maybeLst = [[['sam', 2],'1'],['dad','21']]
print intify(maybeLst) 
like image 44
Ray Avatar answered Nov 03 '22 05:11

Ray