在python中切片列表的一种优雅方法,给出了另一个要切片的id列表

时间:2016-07-10 10:17:05

标签: python slice

我正在寻找一种优雅的方法来在python中对列表l进行切片,给出一个id l_ids列表。 例如,而不是写

new_list = [l[i] for i in l_ids] 

写一些像(伪代码):

new_list = l[*l_ids] 

切片列表有类似的方法吗?

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

编辑:可以假设所有列表项都属于同一类型

5 个答案:

答案 0 :(得分:6)

您可以像这样使用operator.itemgetter(*items)

from operator import itemgetter

getter = itemgetter(*lst_ids)
new_list = list(getter(lst))

另请注意,我已将l变量重命名为lst,因为它不那么模糊且should be avoided

你可以使用Python 3解压缩隐式地将元组强制转换为列表,正如@JonClements所评论的那样:

*new_list, = getter(lst)

最后,从Python 3.5开始,您还可以使用扩展解包:

new_list = [*getter(lst)]

答案 1 :(得分:2)

我认为进口任何东西都不是特别优雅,或者是pythonic。

列表理解工作,我无法看到不使用它们的理由(或没有充分的理由导入某些东西来做同样的事情):

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

这种理解对我来说看起来很诡异和优雅。

答案 2 :(得分:1)

您可以使用itemgetter

  var $scrollable = $('.scrollable');
  var $scrollbar  = $('.scrollbar');
  $scrollable.outerHeight(true);
  var H   = $scrollable.outerHeight(true);
  var sH  = $scrollable[0].scrollHeight;
  var  sbH = H*H/sH;



$('.scrollbar').height(sbH);

$scrollable.on("scroll", function(){

    $scrollbar.css({top: $scrollable.scrollTop()/H*sbH });
});
  

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

答案 3 :(得分:1)

我会选择 itemgetter ,但你也可以映射 list .__ getitem _ _:

l = ['a', 'b', 'c', 'd', 'e']
l_ids = [1, 2, 3]

new = list(map(l.__getitem__, l_ids))

答案 4 :(得分:0)

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

from numpy import *
new_list = array(l)[l_ids]
相关问题