我们如何获取特定索引列表的元素?

时间:2015-06-18 22:52:06

标签: python list indexing

我有一个python列表说

a= ['Sample Date', '4/21/2015', '10/14/2014', '9/16/2014', '7/10/2014', '8/11/2014', '8/3/2014', '7/20/2014', '7/6/2014', '8/11/2014', '8/11/2014', '8/11/2014'] 

我有一个索引列表属于列表说

b=[5, 9, 10, 11].

获取以下输出的代码应该是什么

c= ['7/20/2014', '7/6/2014','7/20/2014', '7/6/2014']

2 个答案:

答案 0 :(得分:4)

使用简单的列表理解

(mat*)[i]

或者

>>> a= ['Sample Date', '4/21/2015', '10/14/2014', '9/16/2014', '7/10/2014', '8/11/2014', '8/3/2014', '7/20/2014', '7/6/2014', '8/11/2014', '8/11/2014', '8/11/2014'] 
>>> b=[5, 9, 10, 11]
>>> [a[i-1] for i in b]
['7/10/2014', '7/6/2014', '8/11/2014', '8/11/2014']

如果它来自>>> [a[i] for i in b] ['8/11/2014', '8/11/2014', '8/11/2014', '8/11/2014'] 索引

答案 1 :(得分:3)

operator.itemgetter 正是这样做

>>> from operator import itemgetter
>>> a = ['Sample Date', '4/21/2015', '10/14/2014', '9/16/2014', '7/10/2014', '8/11/2014', '8/3/2014', '7/20/2014', '7/6/2014', '8/11/2014', '8/11/2014', '8/11/2014'] 
>>> getitems = itemgetter(5, 9, 10, 11)
>>> getitems(a)
('8/11/2014', '8/11/2014', '8/11/2014', '8/11/2014')