python-3.xtype-conversionstarmap

Converting "Pre-Zipped" list values to integers


I frequently have a list of "pre-zipped" (elements are lists) data. I'm trying to convert each item to an integer (from an input string, usually).

How can I make each element in a complex list into an integer?

I initially attempted a list comprehension:

ls = ["1", "2", ["3", "4", "5"], "6"]
ls = [int(i) for i in ls]

But the int function can't take an iterable, so it breaks on int(["3", "4", "5"])


Looking around, I learned about the map() function, which applies a function to each item in an iterable.

ls = ["1", "2", ["3", "4", "5"], "6"]

print(map(lambda x: int(x), ls))

The above code outputs

<map object at 0x000001A84C46E898>

But when I attempt to convert that to a list, I get an error

ls = ["1", "2", ["3", "4", "5"], "6"]

print(list(map(lambda x: int(x), ls)))
TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'

So that sounds to me like map is passing the int() function the list. I also tried itertools.starmap():

import itertools

ls = ["1", "2", ["3", "4", "5"], "6"]

print(list(itertools.starmap(lambda x: int(x), ls)))

This, however, seems to behave the same as map(): returning a map object that can't be converted to a list.


Help is really appreciated. Thanks!


Solution

  • You can use exeption handling on things that throw on int(thing):

    def makeInt(data):
        try:
            k = int(data)
        except ValueError:
            k = [makeInt(d) for d in data]
        return k
    
    ls = ["1", "2", ["3", "4", "5"], "6"]
    
    t = makeInt(ls)
    print(t) 
    

    Output:

    [1, 2, [3, 4, 5], 6]
    

    This will still fail if you supply non-integer data into your lists.