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

2024-04-24 14:39:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个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'] 

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

^{pr2}$

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

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

Tags: sample代码列表datepr2
2条回答

使用简单的列表理解

>>> 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']

或者

^{pr2}$

如果它基于第0个索引

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')

相关问题 更多 >