Python 一种优雅的方法,在给定另一个ID列表的情况下对列表进行切片

Python 一种优雅的方法,在给定另一个ID列表的情况下对列表进行切片,python,slice,Python,Slice,我正在寻找一种优雅的方法来在python中分割列表l,给定一个ID列表l\u id。 比如说,不是写作 new_list = [l[i] for i in l_ids] 编写类似(伪代码)的代码: 有没有类似的方法来分割列表 我觉得已经有人问过了,但我找不到任何参考资料 编辑:可以假定所有列表项的类型相同吗?您可以这样使用: from operator import itemgetter getter = itemgetter(*lst_ids) new_list = list(gette

我正在寻找一种优雅的方法来在python中分割列表
l
,给定一个ID列表
l\u id
。 比如说,不是写作

new_list = [l[i] for i in l_ids] 
编写类似(伪代码)的代码:

有没有类似的方法来分割列表

我觉得已经有人问过了,但我找不到任何参考资料

编辑:可以假定所有列表项的类型相同吗?

您可以这样使用:

from operator import itemgetter

getter = itemgetter(*lst_ids)
new_list = list(getter(lst))
另外,请注意,我将
l
变量重命名为
lst
,因为它不那么模棱两可,也不那么复杂

您可以使用Python 3解包将元组隐式转换为列表,正如@JonClements所评论的:

*new_list, = getter(lst)
最后,自Python 3.5以来,您还可以使用扩展解包:

new_list = [*getter(lst)]
你可以用

['b','c','d']


我不认为进口任何东西是特别优雅的,或者说是蟒蛇式的

列表理解是有效的,我看不出有什么理由不使用它们(或者没有很好的理由导入一些东西来做同样的事情):

列表理解正在执行以下操作:

indexes = [3,5,7,0,1,4,2,6]
data = ['a','b','c','d','e','f','g','h']
nList = []
for index in indexes:
    nList += [data[index]]
对我来说,这个理解看起来很有吸引力和优雅。

我会选择itemgetter,但你也可以映射列表。\uuu getitem\uuuuuu:


如果所有列表元素的类型相同,则可以使用numpy:

from numpy import *
new_list = array(l)[l_ids]

itemgetter如果作者只需要创建这样一个列表一次,我认为列表理解是非常好的,但是
itemgetter()。我想,如果您对多个数据列表使用相同的ID列表,速度会慢一些。我不确定是否应该使用带双前导和尾随下划线的方法,它是Python内部保留的,不是吗?这是一个意见问题,我和其他许多人经常使用相同的逻辑,以避免在map中使用lambda调用,过滤器,即一些过滤器集。过滤器中包含\uuuuu vs lambda st:x等。如果您要提到3.5中的扩展解包,请不要忘记还有其他解包可以在3系列中使用(尽管它不是很漂亮)
*new\u lst,=getter(lst)
(以及因为
list()
将全面工作,并说明它的含义-无论如何,我会坚持这一点…)如果您使用numpy,那么这是一个完全不同的问题numpy是一个与operator(使用itemgetter)相同的包。如果它提供了一个有用且简洁的解决方案,我看不出有什么问题。
>>> x = [3,5,7,0,1,4,2,6]
>>> y = ['a','b','c','d','e','f','g','h']
>>> nList = [y[i] for i in x]
>>> nList
['d', 'f', 'h', 'a', 'b', 'e', 'c', 'g']
indexes = [3,5,7,0,1,4,2,6]
data = ['a','b','c','d','e','f','g','h']
nList = []
for index in indexes:
    nList += [data[index]]
l = ['a', 'b', 'c', 'd', 'e']
l_ids = [1, 2, 3]

new = list(map(l.__getitem__, l_ids))
from numpy import *
new_list = array(l)[l_ids]