Braian Braian - 1 year ago 87
Python Question

Subtraction between two nested list of stings in python

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']
the following code is used for reaching to equation c = b - a:

diffs = []
for i, j in zip(a, b):
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 Source

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):
            diffs.append(str(float(k) - float(l)))
        except ValueError:
            diffs.append('-'.join([k, l]))

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download