Python 从给定列表和给定索引中提取列表
我有一个或多或少包含随机值的列表。列表始终具有固定长度。 我还有一个包含整数值的列表。这些值始终小于第一个列表的长度 我想计算一个包含第一个列表中所有值的列表,其索引由第二个列表中的值描述。 我得出了以下结论:Python 从给定列表和给定索引中提取列表,python,list,Python,List,我有一个或多或少包含随机值的列表。列表始终具有固定长度。 我还有一个包含整数值的列表。这些值始终小于第一个列表的长度 我想计算一个包含第一个列表中所有值的列表,其索引由第二个列表中的值描述。 我得出了以下结论: >>> values = ['000', '111', '222', '333', '444', '555', '666', '777'] >>> indices = [2, 4, 7] >>> [v for i, v in enum
>>> values = ['000', '111', '222', '333', '444', '555', '666', '777']
>>> indices = [2, 4, 7]
>>> [v for i, v in enumerate(values) if i in indices]
['222', '444', '777']
由于我的列表很小(24个元素),这对我来说没问题。无论如何,我想知道是否有更优雅的解决方案不计算临时列表(使用enumerate()
)
>>> [values[index] for index in indices]
['222', '444', '777']
>>> from operator import itemgetter
>>> itemgetter(*indices)(values)
('222', '444', '777')
>>> list(itemgetter(*indices)(values))
['222', '444', '777']
>>> map(values.__getitem__, indices)
['222', '444', '777']
map
调用神奇的方法,\uuuu getitem\uuuu
,如下所示
>>> from operator import itemgetter
>>> itemgetter(*indices)(values)
('222', '444', '777')
>>> list(itemgetter(*indices)(values))
['222', '444', '777']
>>> map(values.__getitem__, indices)
['222', '444', '777']
如果您使用的是Python3.x,那么您可能希望将list
与map
>>> list(map(values.__getitem__, indices))
['222', '444', '777']
next
来获取所需的值
>>> filtered = (values[index] for index in indices)
>>> next(filtered)
'222'
>>> next(filtered)
'444'
>>> next(filtered)
'777'
>>> next(filtered)
Traceback (most recent call last):
File "<input>", line 1, in <module>
StopIteration
它不计算临时列表(使用
enumerate()
)-enumerate
不会创建临时列表。嗯,你说得对,它返回一个迭代器,即使在python2中也是如此。