python,从另外两个具有索引的列表创建一系列列表

python, create a series of lists from two other lists with index

您好,提前感谢您的帮助,过去几个月我一直在努力自学 python!

我有两个列表列表:

countries_list =  [['Canada'], ['China'], ['Finland'], ...]
ratios = [[10.2, 10.3, 11.4,  12.0], [8.2, 8.1, 9.0, 9.1], [15.4, 15.5, 15.8, 16.0], ...]

我想根据索引将列表合并在一起。例如,countries[0] = ['Canada']ratios[0] = [10.2, 10.3, 11.4, 12.0]。我想使用索引来创建这个最终列表:

final_list = [[10.2, 10.3, 11.4,  12.0, 'Canada'], [8.2, 8.1, 9.0, 9.1,'China'], [15.4, 15.5, 15.8, 16.0, 'Finland']...]

这是我现在想出的代码:

final_list = []
for countries in countries_list:
    for ratio_list in ratios:
        current_ratios = []
        for r in ratio_list:
            current_ratios.append(r)
        current_ratios.append(countries)
    rows_list.append(current_ratios)
print(rows_list)

这是输出:

[[9.8, 10.3, 10.9, 11.4, 12.0, 12.6, 14.8, 19.2, 25.2, 'Eswatini'], [9.8, 10.3, 10.9, 11.4, 12.0, 12.6, 14.8, 19.2, 25.2, 'Bahamas'], [9.8, 10.3, 10.9, 11.4, 12.0, 12.6, 14.8, 19.2, 25.2, 'Jamaica'], [9.8, 10.3, 10.9, 11.4, 12.0, 12.6, 14.8, 19.2, 25.2, 'Chad'], [9.8, 10.3, 10.9, 11.4, 12.0, 12.6, 14.8, 19.2, 25.2, 'Kenya'], [9.8, 10.3, 10.9, 11.4, 12.0, 12.6, 14.8, 19.2, 25.2, 'Mali'], [9.8, 10.3, 10.9, 11.4, 12.0, 12.6, 14.8, 19.2, 25.2, 'Guyana'] ...]

如您所见,它有点接近预期的结果,但比率始终相同。嵌套循环让我非常困惑,我发现自己想知道顺序是什么以及这里发生了什么。

您可以使用 zip() + 列表理解:

countries_list = [["Canada"], ["China"], ["Finland"]]
ratios = [
    [10.2, 10.3, 11.4, 12.0],
    [8.2, 8.1, 9.0, 9.1],
    [15.4, 15.5, 15.8, 16.0],
]

out = [[*r, *c] for c, r in zip(countries_list, ratios)]
print(out)

打印:

[
    [10.2, 10.3, 11.4, 12.0, "Canada"],
    [8.2, 8.1, 9.0, 9.1, "China"],
    [15.4, 15.5, 15.8, 16.0, "Finland"],
]