Gabriel Gabriel - 4 months ago 8
Python Question

Map unique repeated floats stored in list to strings

Say I have 5 unique floats that are randomly repeated and stored in a list. E.g.:

a = [0.1, 0.5, 8.3, 0.5, 4.6, 9.2, 0.1, 8.3, 9.2, 9.2, 4.6]


where the 5 floats are:
0.1, 0.5, 8.3, 9.2, 4.6
.

I want to go through this list, and assign a given string to a variable, depending on which float is pulled from the list. The only way I can think of doing this currently is using several
if
statements:

var_store = []
for f in a:
if f == 0.1:
var = 'aa'
elif f = 0.5:
var = 'bb'
elif f = 9.2:
var = 'cc'
elif f = 8.3:
var = 'dd'
elif f = 4.6:
var = 'ee'
var_store.append(var)


So I end up with a
var_store
list of strings, where each float was mapped to a given string.

Now consider I have lots of such floats, such that the
if
block needs to be rather large.

Is there a way to somehow map each float to a string and generate the
var_store
list without having to use dozens of
if
lines?

Answer

You can use a combination of map() and a dictionary translating numbers into strings.

>>> a = [0.1, 0.5, ...]
>>> lookup = {0.1: 'aa', 0.5: 'bb', ...}
>>> var_store = map(lambda x: lookup.get(x), a)
>>> list(var_store)
['aa', 'bb', ...]

By the way, in case of an "unknown" number not in the lookup, this will put None in the list.