I am trying to find a method to include a second variable in a 2D array. Additionally I only want to assign a second variable to cells that allready have one. for instance, I start with the array:
seq = [[1, 0, 0, 0],[1, 2, 3, 4],[2, 0, 0, 0]]
and I want to assign a second integer to the values that allready have one, making this:
seq = [[(1, a), 0, 0, 0],[(1, b), (2, c), (3, d), (4, e)], [(2, f), 0, 0, 0]]
in which I ideally want a loop in which i can select the particular values with a rule. I don't know for sure I can keep the 0's in the particular positions without assigning a second value to them, or if the array needs to be converted to a list. I'm quite new to python and normally work with Matlab.
CodePudding user response:
Perhaps something like this would work:
import string
from itertools import cycle
letters = cycle(string.ascii_lowercase)
seq = [[1, 0, 0, 0], [1, 2, 3, 4], [2, 0, 0, 0]]
for i, s in enumerate(seq):
seq[i] = [(k, next(letters)) if k > 0 else k for e, k in enumerate(s)]
print(seq)
>>> [[(1, 'a'), 0, 0, 0], [(1, 'b'), (2, 'c'), (3, 'd'), (4, 'e')], [(2, 'f'), 0, 0, 0]]
CodePudding user response:
Try:
values = list('abcdef')
result = list()
for row in seq:
result.append([(n, values.pop(0)) if n!=0 else 0 for n in row])
>>> result
[[(1, 'a'), 0, 0, 0],
[(1, 'b'), (2, 'c'), (3, 'd'), (4, 'e')],
[(2, 'f'), 0, 0, 0]]