返回基于索引列表的子列表的最简单,最有效的函数是什么? [英] What is the simplest and most efficient function to return a sublist based on an index list?

查看:54
本文介绍了返回基于索引列表的子列表的最简单,最有效的函数是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个列表l:

['a','b','c','d','e']

和索引列表idx:

[1,3]

将返回的最简单,最有效的函数是什么?

What is the simplest and most efficient function that will return:

['b','d']

推荐答案

以下是使用列表理解的选项:

Here is an option using a list comprehension:

[v for i, v in enumerate(l) if i in idx]

如果先将idx转换为集合,则效率会更高.

This will be more efficient if you convert idx to a set first.

operator.itemgetter的替代项:

import operator
operator.itemgetter(*idx)(l)

如评论中所述,[l[i] for i in idx]可能是您最好的选择,除非idx的索引可能大于l的长度,或者如果idx没有排序并且您希望保持相同以l的顺序订购.

As noted in comments, [l[i] for i in idx] will probably be your best bet here, unless idx may contain indices greater than the length of l, or if idx is not ordered and you want to keep the same order as l.

这篇关于返回基于索引列表的子列表的最简单,最有效的函数是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆