1

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.

Augis
  • 79
  • 6
  • 1
    `list(map(lambda`??? Use a list comprehension instead: `[[int(x) if x.isdigit() else x for x in ele] for ele in test_list]` (using @eumiro's fixed version) – wjandrea Feb 10 '20 at 18:18
  • BTW `str.isdigit()` doesn't tell you if a string is a valid `int`. See for example [this answer and all the caveats and comments](https://stackoverflow.com/a/1265696/4518341). You should use a try-except instead if you're going to be handling anything else, even negative numbers. – wjandrea Feb 10 '20 at 18:23

3 Answers3

4

Why use map if you already know the positions are correct for each sub-list

res = [[int(x), int(y), z] for x, y, z in test_list] 

Result

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

Or even better since this could be dict in the end use a dict comprehension:

res = {int(i): {'price': int(p), 'name': n} for i, p, n in test_list}

Result

{1: {'price': 350, 'name': 'apartment'}, 2: {'price': 300, 'name': 'house'}, 3: {'price': 300, 'name': 'flat'}, 4: {'price': 250, 'name': 'apartment'}}
Jab
  • 26,853
  • 21
  • 75
  • 114
2

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

eumiro
  • 207,213
  • 34
  • 299
  • 261
1

Try this:

test_list = [[int(ele) if ele.isdigit() else ele for ele in elem ] for elem in test_list]
Saurav Joshi
  • 414
  • 5
  • 13