Python 我们如何获取特定索引列表中的元素?
我有一个python列表Python 我们如何获取特定索引列表中的元素?,python,list,indexing,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/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].
要获得以下输出,代码应该是什么
c= ['7/20/2014', '7/6/2014','7/20/2014', '7/6/2014']
使用简单的列表理解
>>> 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']
或
如果它基于0
th索引
确实如此
>>> 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')
b
中的索引如何与a
相关,从而使c
。我的意思是a
中的第5个索引不是'7/20/2014'而是'8/11/2014'。你能展示一下itemgetter的代码是什么样子吗?这在Python 2中有效吗?我得到:name错误:name'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')