首页 > 解决方案 > Mapping item in a list to a list of lists

问题描述

I'm thinking of an efficient way to map names in a list to grouped index items in a list of lists.

Let's say I have this grouping:

g = [[0,1],[2]]

I also have this list:

names = ["canine", "dog", "feline"]

I want to return the mapped names to the grouping according to index:

result = [["canine","dog"], ["feline"]]

I'm not exactly sure how to do this or even how to do it efficiently. Here's what I have so far and it's not working.

final = []
for j in range(len(names)):
    for item in g:
        for inner in item:
            res = []
            if inner == j:
                res.append(names[inner])
        final.append(res)
print(final)

Any tips would be appreciated.

标签: pythonfor-loopiteration

解决方案


我想你可能想要循环gnot names。没有理由循环,names因为您将使用 values 对其进行索引g。在这种情况下,似乎一个简单的列表理解可能更适合这个:

[[names[i] for i in sublist] for sublist in g]

推荐阅读