# (1)
data_list = [
    {"city1": "北京", "city2": "纽约", "go": 50.3, "come": 60.5},
    {"city1": "上海", "city2": "洛杉矶", "go": 60, "come": 40},
    {"city1": "广州", "city2": "芝加哥", "go": 30, "come": 20},
]

to_america = 0
to_china = 0
for item in data_list:
    to_america += item["go"]
    to_china += item["come"]

# (2)
import pandas as pd

data_list = [
    {"city1": "北京", "city2": "纽约", "go": 50.3, "come": 60.5},
    {"city1": "上海", "city2": "洛杉矶", "go": 60, "come": 40},
    {"city1": "广州", "city2": "芝加哥", "go": 30, "come": 20},
    {"city1": "北京", "city2": "芝加哥", "go": 30, "come": 20},
]


def calculate_go_come(city1, city2):
    for data in data_list:
        if data["city1"] == city1 and data["city2"] == city2:
            return data["go"] - data["come"]
    return None

# print(calculate_go_come("上海", "洛杉矶"))

index = set([data["city1"] for data in data_list])
col = set([data["city2"] for data in data_list])
data_frame = pd.DataFrame(index=list(index), columns=list(col), data=0.0)
for i in range(len(data_list)):
    for j in range(len(data_list)):
        city1 = data_list[i]["city1"]
        city2 = data_list[j]["city2"]
        difference = calculate_go_come(city1, city2)
        data_frame.loc[city1, city2] = difference
print(data_frame)