How to query a nested tuple by index using a list to represent the index?
Question:
Get the value of a nested tuple at certain index like so:
tup = ((-3, (6, 15), 3), -9, ((-3, -6, 9, -5), -2))
print(tup[0][1][1])
>> 15
Want to query a nested tuple by index using as a list to represent the index, something like:
def getTupValue(input_tuple, input_list=[])
## returns the value at for example: tup[0][1][1]
getTupValue(tup, [0, 1, 1])
## returns 15
Answers:
If you’re sure that there won’t be index errors, you can simply do:
def get_by_indexes(tup, indexes):
for index in indexes:
tup = tup[index]
return tup
mytuple = ((-3, (6, 15), 3), -9, ((-3, -6, 9, -5), -2))
print(get_by_indexes(mytuple, [0, 1, 1]))
Output:
15
You can use functools.reduce
:
from functools import reduce
tup = ((-3, (6, 15), 3), -9, ((-3, -6, 9, -5), -2))
def getTupValue(input_tuple, input_list):
return reduce(lambda x, y: x[y], input_list, input_tuple)
print(getTupValue(tup, [0, 1, 1]))
Prints:
15
def getTupValue(input_tuple, input_list: list=None):
if input_list in [None, []]:
return input_tuple
return getTupValue(input_tuple[input_list.pop(0)], input_list)
tup = ((-3, (6, 15), 3), -9, ((-3, -6, 9, -5), -2))
getTupValue(tup, input_list=[0,1,1])
Get the value of a nested tuple at certain index like so:
tup = ((-3, (6, 15), 3), -9, ((-3, -6, 9, -5), -2))
print(tup[0][1][1])
>> 15
Want to query a nested tuple by index using as a list to represent the index, something like:
def getTupValue(input_tuple, input_list=[])
## returns the value at for example: tup[0][1][1]
getTupValue(tup, [0, 1, 1])
## returns 15
If you’re sure that there won’t be index errors, you can simply do:
def get_by_indexes(tup, indexes):
for index in indexes:
tup = tup[index]
return tup
mytuple = ((-3, (6, 15), 3), -9, ((-3, -6, 9, -5), -2))
print(get_by_indexes(mytuple, [0, 1, 1]))
Output:
15
You can use functools.reduce
:
from functools import reduce
tup = ((-3, (6, 15), 3), -9, ((-3, -6, 9, -5), -2))
def getTupValue(input_tuple, input_list):
return reduce(lambda x, y: x[y], input_list, input_tuple)
print(getTupValue(tup, [0, 1, 1]))
Prints:
15
def getTupValue(input_tuple, input_list: list=None):
if input_list in [None, []]:
return input_tuple
return getTupValue(input_tuple[input_list.pop(0)], input_list)
tup = ((-3, (6, 15), 3), -9, ((-3, -6, 9, -5), -2))
getTupValue(tup, input_list=[0,1,1])