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

查看:30
本文介绍了从具有特定索引的 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天全站免登陆