简体   繁体   English

从给定列表和给定索引中提取列表

[英]Extract list from given list and given indices

I have a list containinig, more or less, random values. 我有一个列表containsinig,或多或少,随机值。 The list always has a fixed length. 列表始终具有固定长度。 I have another list containing integer values. 我有另一个包含整数值的列表。 These values are always smaller than the length of the first list. 这些值始终小于第一个列表的长度。

I want to calculate a list containing all values from the first list whose indices are described by the values in the second list. 我想计算一个列表,其中包含第一个列表中的所有值,其索引由第二个列表中的值描述。 I came up with the following: 我想出了以下内容:

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

As my lists are rather small (24 elements) this is OK for me. 由于我的名单相当小(24个元素),这对我来说没问题。 Anyway, I wonder if there is some more elegant solution which does not calculate a temporary list (with enumerate() ). 无论如何,我想知道是否有更优雅的解决方案,不计算临时列表(使用enumerate() )。

>>> values = ['000', '111', '222', '333', '444', '555', '666', '777']
>>> indices = [2, 4, 7]
  1. You can use a simple list comprehension 您可以使用简单的列表理解

     >>> [values[index] for index in indices] ['222', '444', '777'] 
  2. You can use operator.itemgetter , like this 您可以像这样使用operator.itemgetter

     >>> from operator import itemgetter >>> itemgetter(*indices)(values) ('222', '444', '777') >>> list(itemgetter(*indices)(values)) ['222', '444', '777'] 
  3. Or you can invoke the magic method, __getitem__ with map , like this 或者你可以像这样用map调用魔术方法__getitem__

     >>> map(values.__getitem__, indices) ['222', '444', '777'] 

    If you are using Python 3.x, then you might want to use list with map 如果您使用的是Python 3.x,那么您可能希望将listmap配合使用

     >>> list(map(values.__getitem__, indices)) ['222', '444', '777'] 
  4. If you don't want to create the entire list, then you can create a generator expression and use next with that to get the values whenever you want. 如果您不想创建整个列表,那么您可以创建一个生成器表达式并使用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 

    If you are going to just iterate the result, then I would recommend using the generator expression approach. 如果您只是迭代结果,那么我建议使用生成器表达式方法。

     >>> for item in (values[index] for index in indices): ... print(item + ' ' + item) ... 222 222 444 444 777 777 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM