python - How to deal with cycling through an unknown number of indexes in an array or list -
for example, had file containing names of variables such foo or bar[4][5] names may or may not have variable number of indexes, variables have been multidimensional arrays. inside dictionary starting memory address of each variable, , type of value was, such int_32 or signed_int_64, etc.
my program supposed make print out of each variable, , each component of arrays, memory address , value. problem was, how deal arrays? 1 dimensional, 2 dimensional, twelve dimensional or 0 dimensional (single value) needed them 1 program. important factor making program robust enough endure number of dimensions.
my solutions take name , check if matched regex formula provided user of stackoverflow. following code should credited lib.
def getentryname(var_string) : # lib @ stackoverflow.com result = re.search(r'(.*?)((?:\[\d*])*)$', var_string) var_name = result.group(1) numbers = re.findall(r'\[(\d+)]', result.group(2)) return var_name, numbers
this returns base name of variable , list called "numbers" contains of indexes of of arrays.
now used recurvise call find iterate through number of indexes!
def brackethandler( passedrange, var_name, var_length, var_starta, numbers ) in range( 0, int( passedrange ) - 1 ) : # cycle through it! if numbers : # if there more indexes cycle through, brackethandler( numbers[0], var_name + "[" + str( ) + "]", var_length, var_starta, numbers[1:] ) else: # exit condition processvar(var_name + "[" + str( ) + "]",
var_length, var_starta) var_starta += var_length
now explain code. basically, before function ran, check sure there in numbers, , if there is, pass recursive function first value in numbers, variable's name, length , starting address , rest of numbers (which mich = []) once there, iterate through current index. next check if there more numbers in set, , if there are, tack current index onto name, , run through function again, , until there no new numbers.
at time, there being no new numbers, deal variables in function, , incriment starting address. , viola!
if code takes name foo , set of numbers [4, 6, 8] produce:
foo[0][0][0] foo[0][0][1] ... foo[0][0][7] foo[0][1][0] ... foo[3][5][7]
and send them processed correct value!
there might better solutions, wasn't able find any. tinkered long while make work best could, , while may seem obvious some, less obvious @ time. if have suggestions improve upon it, welcome it. if there error in did, feel free edit mistakes. if not appropriate way q&a, let me know, , delete this!
Comments
Post a Comment