Braian - 3 months ago 21

Python Question

I am trying to follow the used structure in this question for nested lists but I'm confused and don know how to figure it out. Suppose that to subtract the two lists

`a = ['5', '35.1', 'FFD']`

`b = ['8.5', '11.3', 'AMM']`

`diffs = []`

for i, j in zip(a, b):

try:

diffs.append(str(float(j) - float(i)))

except ValueError:

diffs.append('-'.join([j, i]))

>>> print(diffs)

['3.5', '-23.8', 'AMM-FFD']

My question is, how to have C = B - A by considering the following structure:

A = [['X1','X2'],['52.3','119.4'],['45.1','111']]

B = [['Y1','Y2'],['66.9','65'],['99','115.5']]

C = [['Y1-X1','Y2-X2'],['14.6','-54.4'],['53.9','4.5']]

and how to seprate the first and second elements of each internal list, something like:

`Array 1 = ['Y1-X1', '14.6', '53.9']`

Array 2 = ['Y2-X2', '-54.4', '4.5']

I appreciate any kind of help

Answer

Well, if it's guaranteed that the lists will always be 2 levels nested, you can simply add one more loop:

```
diffs_lists = []
for i, j in zip(a, b):
diffs = []
for k, l in zip(i, j):
try:
diffs.append(str(float(k) - float(l)))
except ValueError:
diffs.append('-'.join([k, l]))
diffs_lists.append(diffs)
```

To separate the result in two as you asked, simply use zip:

```
zip(*diffs_lists)
```