Suppose I have a list of values
['small', 'medium', 'large', 'extralarge']
that I would like to map into the numbers [1,2,3,4]
with small
corresponding to 1
, medium
corresponding to 2
, large
corresponding to 3
, and extralarge
corresponding to 4
.
How can I efficiently do such a functional mapping for a new value x
without needing to do something like
if x == "small":
print(1)
elif x == "medium":
...
CodePudding user response:
Use a dictionary:
sizes = ['small', 'medium', 'large', 'extralarge']
mapping = {size: value for value, size in enumerate(sizes, 1)}
Then for some x
,
print(mapping[x])
Which will print the value 1, 2, 3, or 4, based on the value of x
being a some size like "small", "medium", etc...
CodePudding user response:
You can use enumerate()
to bind each string to an index:
for idx, item in enumerate(data, start=1):
if x == item:
print(idx)
CodePudding user response:
You can iterate through them as @BrokenBenchmark suggests. However, you should consider whether a list is the most optimal data structure for your purpose; as @ddejohn suggests, perhaps a dictionary would suit better your purposes as its structure is literally a set of mapped key:value pairs.
CodePudding user response:
If you already have two lists then one way to create dictionary is to use zip:
names = ['small', 'medium', 'large', 'extralarge']
nums = [1,2,3,4]
mapping = dict(zip(names, nums))
If you don't have numbers list and need one number corresponding to the name at the time then you can take advantage of indices. Simple helper function:
names = ['small', 'medium', 'large', 'extralarge']
def get_value(name, list_):
return list_.index(name) 1
print(get_value('medium', names)) # prints 2
Name lookup in similar fashion could look like:
def get_name(num, list_):
return list_[num-1]
print(get_name(2, names)) # prints 'medium'
If you append new names to names list then you don't need to update other parts of your code.