1

I have a data vector data = [x for x in range(0,999)] what I want to do is that to, access elements in data according to a given value e.g if value=10 access 0th index of data and if value=20 access 1st index of data. It is supoused to be something like this:

def get_data(value):
if value ==10:
    return data[0]
elif value == 20:
    return data[1]
elif value ==30:
    return data[2]

But in reality, i will have really big data and I cannot keep putting elif statements. Is there any efficient way of doing this?

Salman Shaukat
  • 333
  • 3
  • 14
  • 1
    You can check [there](https://stackoverflow.com/questions/60208/replacements-for-switch-statement-in-python), may help you.. :) – AntoineLB May 14 '18 at 09:49

2 Answers2

1

One approach could be dividing the value to 10 and then just substract 1 from result.

return data[value//10 - 1]
Mihai Alexandru-Ionut
  • 47,092
  • 13
  • 101
  • 128
1

You can use a dictionary to solve your problem.

def get_data(value):
     return {
         10: data[0],
         20: data[1],
         30: data[2]
     }.get(value, data[3])   #data[3] will be the default value.