我正在寻找一种优雅的方式来在python中切片列表l
,给定一个ids列表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
,因为它不那么模棱两可,应该避免。
您可以使用 Python 3 解包将元组隐式转换为列表,如@JonClements评论的那样:
*new_list, = getter(lst)
最后,从 Python 3.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]]
对我来说,理解看起来非常蟒蛇和优雅。
我会使用 itemgetter,但你也可以映射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]