从python列表中挑选具有特定索引的项目 [英] Picking out items from a python list which have specific indexes

查看:129
本文介绍了从python列表中挑选具有特定索引的项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我敢肯定,有很好的方法可以在Python中做到这一点,但是我是该语言的新手,所以如果这很简单,请原谅我!

I'm sure there's a nice way to do this in Python, but I'm pretty new to the language, so forgive me if this is an easy one!

我有一个列表,我想从该列表中选择某些值.我要选择的值是在另一个列表中指定其索引的值.

I have a list, and I'd like to pick out certain values from that list. The values I want to pick out are the ones whose indexes in the list are specified in another list.

例如:

indexes = [2, 4, 5]
main_list = [0, 1, 9, 3, 2, 6, 1, 9, 8]

输出为:

[9, 2, 6]

(即main_list中索引为2、4和5的元素).

(i.e., the elements with indexes 2, 4 and 5 from main_list).

我觉得使用列表理解之类的方法应该可以做到这一点,但是我无法弄清楚(特别是,我无法弄清楚使用列表理解时如何访问项目的索引).

I have a feeling this should be doable using something like list comprehensions, but I can't figure it out (in particular, I can't figure out how to access the index of an item when using a list comprehension).

推荐答案

[main_list[x] for x in indexes]

这将使用列表推导返回对象列表.

This will return a list of the objects, using a list comprehension.

这篇关于从python列表中挑选具有特定索引的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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