Home > Back-end >  Iterating on a list based on different parameters
Iterating on a list based on different parameters

Time:05-03

I'm once again asking for help on iterating over a list. This is the problem that eludes me this time:

I have this table:

Table

that contains various combinations of countries with their relative trade flow.

Since trade goes both ways, my list has for example one value for ALB-ARM (how much albania traded with armenia that year) and then down the list another value for ARM-ALB (the other way around).

I want to sum this two trade values for every pair of countries; and I've been trying around with some code but I quickly realise how all my approaches are wrong.

How do I even set it up? I feel like it's too hard with a loop and it will be easy with some function that I don't even know exists.

Example data in Table format:

from astropy.table import Table
country1 = ["ALB","ALB","ARM","ARM","AZE","AZE"]
country2 = ["ARM","AZE","ALB","AZE","ALB","ARM"]
flow = [500,0,200,300,90,20]

t = Table([country1,country2,flow],names=["1","2","flow"],meta={"Header":"Table"})

and the expected output would be:

trade = [700,90,700,320,90,320]
result = Table([country1,country2,flow,trade],names=["1","2","flow","trade"],meta={"Header":"Table"})

Thank you in advance all

CodePudding user response:

Maybe this could help:

country1 = ["ALB","ALB","ARM","ARM","AZE","AZE"]
country2 = ["ARM","AZE","ALB","AZE","ALB","ARM"]
flow = [500,0,200,300,90,20]
trade = []


pairs = map(lambda t: '-'.join(t), zip(country1, country2))
flow_map = dict(zip(pairs, flow))
for left_country, right_country in zip(country1, country2):
    trade.append(flow_map['-'.join((left_country, right_country))]   flow_map['-'.join((right_country, left_country))])

print(trade)

outputs:

[700, 90, 700, 320, 90, 320]
  • Related