如何在Python中使用索引从列表中提取元素? [英] How to extract elements from a list using indices in Python?

查看:877
本文介绍了如何在Python中使用索引从列表中提取元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果您在python中有一个列表,并且想要将索引1、2和5处的元素提取到新列表中,您将如何做?

If you have a list in python, and want to extract elements at indices 1, 2 and 5 into a new list, how would you do this?

这是我的操作方式,但我不太满意:

This is how I did it, but I'm not very satisfied:

>>> a
[10, 11, 12, 13, 14, 15]
>>> [x[1] for x in enumerate(a) if x[0] in [1,2,5]]
[11, 12, 15]

有更好的方法吗?

总的来说,给定一个索引元组,即使重复,您将如何使用该元组从列表中提取相应的元素(例如,元组(1,1,2,1,5)产生[11,11,12,11,15]).

More in general, given a tuple of indices, how would you use this tuple to extract the corresponding elements from a list, even with duplication (e.g. tuple (1,1,2,1,5) produces [11,11,12,11,15]).

推荐答案

也许使用此:

[a[i] for i in (1,2,5)]
# [11, 12, 15]

这篇关于如何在Python中使用索引从列表中提取元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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