Python:按索引过滤列表 [英] Python: filtering lists by indices

查看:34
本文介绍了Python:按索引过滤列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Python 中,我有一个元素列表 aList 和一个索引列表 myIndi​​ces.有什么方法可以一次检索 aList 中的所有项目,并将 myIndi​​ces 中的值作为索引?

示例:

<预><代码>>>>aList = ['a', 'b', 'c', 'd', 'e', 'f', 'g']>>>我的指数 = [0, 3, 4]>>>aList.A_FUNCTION(myIndi​​ces)['a', 'd', 'e']

解决方案

我不知道有什么方法可以做到.但是你可以使用列表理解:

<预><代码>>>>[aList[i] for i in myIndi​​ces]

In Python I have a list of elements aList and a list of indices myIndices. Is there any way I can retrieve all at once those items in aList having as indices the values in myIndices?

Example:

>>> aList = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> myIndices = [0, 3, 4]
>>> aList.A_FUNCTION(myIndices)
['a', 'd', 'e']

解决方案

I don't know any method to do it. But you could use a list comprehension:

>>> [aList[i] for i in myIndices]

这篇关于Python:按索引过滤列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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