Search code examples
pythonlistnestedmixed

Python string 2d list to mixed int/string list


Got this list:

test_list = [['1', '350', 'apartment'], ['2', '300', 'house'], ['3', '300', 'flat'], ['4', '250', 'apartment']]

Trying to get mixed list like

test_list = [[1, 350, 'apartment'], [2, 300, 'house'], [3, 300, 'flat'], [4, 250, 'apartment']]

So far my attempt:

res = [list(map(lambda ele : int(ele) if ele.isdigit()  
          else ele, test_list)) for ele in test_list ] 

But doesn't seem to be working.


Solution

  • You have just a tiny problem with the variables.

    In this fix, test_list is the whole list, ele is ['1', '350', 'apartment'] and x is one single string out of it.

    [list(map(lambda x: int(x) if x.isdigit() else x, ele)) for ele in test_list]
    

    but better use a list comprehension instead of list(map(:

    [[int(x) if x.isdigit() else x for x in ele] for ele in test_list]
    

    Even better: a list of dicts or list of tuples would be more appropriate. A list is usually a collection of elements without specific role of each one of them.

    [{'id': int(id), 'price': int(price), 'name': name} for id, price, name in test_list]
    
    [(int(id), int(price), name) for id, price, name in test_list]
    

    would also prevent you from converting a third item (name in my example) to integer if it was randomly called "123".