python - 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.
解决方案
我想你可能想要循环g
not names
。没有理由循环,names
因为您将使用 values 对其进行索引g
。在这种情况下,似乎一个简单的列表理解可能更适合这个:
[[names[i] for i in sublist] for sublist in g]
推荐阅读
- javascript - Getting the result of an if else statement out of scope in Javascript
- swift - AdMob 广告未展示
- php - MYSQL 中时间戳更新的奇怪问题
- php - How to post to different categories in wordpress using a custom php script
- r - 如何在箱线图中添加线条和文本?
- c# - 有人可以(很好地)解释为什么 OOP 方法重载是一件好事吗?
- entity-framework - Entity Framework Core:用户定义的 SQL 函数
- javascript - 通过 API 发布请求将数十万个 JSON 对象发送到数据库
- python - matplotlib/cartopy Mollweide 投影中经度环绕的接缝
- mysql - MySQL Installer not launching on Windows 7