Home > Back-end >  performing operations on values in 2-D list and appending each sub-list to new list
performing operations on values in 2-D list and appending each sub-list to new list

Time:04-14

I have two 2-D python array lists. I want to on each value in each array perform an operation on each other and append that value into a list while retaining the 2-D structure.

For example I have

list1 = [[1,2,3],[4,5,6],[7,8,9]]
list2 = [[3,2,1],[6,5,4],[9,8,7]]

I want to do so that (for example just simple addition) the output is

output_list: [[4,4,4],[10,10,10],[16,16,16]]

In my case, I am calculating the standard deviation.

I have two 2-D lists named rolling_mean and mean_std that I am doing parallel iteration over and appending to an list named lower_bound

lower_bound = []
    

    for k,h in zip(range(len(rolling_mean)),range(len(mean_std))):
        for l,m in zip(range(len(rolling_mean[k])),range(len(mean_std[h]))):
            lower_bound.append(rolling_mean[k][l] - (1.96 * mean_std[h][m]))

    print(lower_bound)

This is giving me the correct output but the values are all in one single array. I want it to be a 2-D array like the example output above.

CodePudding user response:

...
lb_part = []
for l,m ...
    lb_part.append(...)
lower_bound.append(lb_part)

CodePudding user response:

Generic functions reczip and recmap may be useful to you -

def reczip(a,b,f=tuple):
  if isinstance(a, list) and isinstance(b, list):
    return list(reczip(v, b[i], f) for (i,v) in enumerate(a))
  else:
    return f((a,b))
x = [[1,2,3],[[4],[5,6]],9]
y = [[3,2,1],[[6],[5,4]],9]
print(reczip(x,y))
[[(1, 3), (2, 2), (3, 1)], [[(4, 6)], [(5, 5), (6, 4)]], (9, 9)]
def recmap(a,f):
  if isinstance(a, list):
    return list(recmap(v, f) for v in a)
  else:
    return f(a)
print(recmap(reczip(x,y),sum))
[[4, 4, 4], [[10], [10, 10]], 18]

As you can see, these work on lists of any nesting level. However, if reczip encounters an asymmetrical shape, you can handle accordingly -

def reczip(a,b,f=tuple):
  try:
    if isinstance(a, list) and isinstance(b, list):
      return list(reczip(v, b[i], f) for (i,v) in enumerate(a))
    else:
      return f((a,b))
  except IndexError:
    return f((a,b)) # when a and b have different number of elements
  • Related