给定另一个要从中切片的 id 列表来切片列表的优雅方法
An elegant way to slice a list given another list of ids to slice from
我正在寻找一种在 python 中分割列表 l
的优雅方法,给定一个 ID 列表 l_ids
。
例如,而不是写
new_list = [l[i] for i in l_ids]
写类似的东西(伪代码):
new_list = l[*l_ids]
有没有类似的切片列表的方法?
我感觉已经有人问过了,但我找不到任何参考资料。
编辑: 可以假设所有列表项都是同一类型吗?
您可以这样使用 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)
最后,从Python3.5开始,还可以使用扩展解包:
new_list = [*getter(lst)]
您可以使用 itemgetter
from operator import itemgetter
l = ['a', 'b', 'c', 'd', 'e']
l_ids = [1, 2, 3]
list(itemgetter(*l_ids)(l))
['b', 'c', 'd']
我不认为导入任何东西特别优雅,或者 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]]
对我来说,理解看起来非常 pythonic 和优雅。
我会选择 itemgetter 但你也可以 map list.__getitem_ _:
l = ['a', 'b', 'c', 'd', 'e']
l_ids = [1, 2, 3]
new = list(map(l.__getitem__, l_ids))
如果所有列表元素都是同一类型,可以使用numpy:
from numpy import *
new_list = array(l)[l_ids]
我正在寻找一种在 python 中分割列表 l
的优雅方法,给定一个 ID 列表 l_ids
。
例如,而不是写
new_list = [l[i] for i in l_ids]
写类似的东西(伪代码):
new_list = l[*l_ids]
有没有类似的切片列表的方法?
我感觉已经有人问过了,但我找不到任何参考资料。
编辑: 可以假设所有列表项都是同一类型吗?
您可以这样使用 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)
最后,从Python3.5开始,还可以使用扩展解包:
new_list = [*getter(lst)]
您可以使用 itemgetter
from operator import itemgetter
l = ['a', 'b', 'c', 'd', 'e']
l_ids = [1, 2, 3]
list(itemgetter(*l_ids)(l))
['b', 'c', 'd']
我不认为导入任何东西特别优雅,或者 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]]
对我来说,理解看起来非常 pythonic 和优雅。
我会选择 itemgetter 但你也可以 map list.__getitem_ _:
l = ['a', 'b', 'c', 'd', 'e']
l_ids = [1, 2, 3]
new = list(map(l.__getitem__, l_ids))
如果所有列表元素都是同一类型,可以使用numpy:
from numpy import *
new_list = array(l)[l_ids]