Python通过索引选择列表中的元素 [英] Python selecting elements in a list by indices

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

问题描述

我在python中有一个列表,想要从中获取一组索引并保存为原始列表的子集:

I have a list in python that I want to get the a set of indexes out of and save as a subset of the original list:

templist = [[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]]

我想要这个:

   sublist=[[1,    4,    7,                      16,      19,20]]

作为示例.

我无法提前知道list元素的内容.我所拥有的就是永远不变的索引.

I have no way of knowing ahead of time what the contents of the list elements will be . All I have is the indices that will always be the same.

有没有一种单行的方法可以做到这一点?

Is there a single line way of doing this?

推荐答案

假设您知道要选择的索引是什么,它的工作原理如下:

Assuming you know what the indices to be selected are, it would work something like this:

indices = [1, 4, 7, 16, 19, 20]
templist = [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21]]
sublist = []

for i in indices:
    sublist.append(templist[i])

这也可以以列表理解的形式表达-

This can also be expressed in the form of a list comprehension -

sublist = [templist[0][i] for i in indices]

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

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