[英]Is there a faster way to extract elements in a list?
suppose I have the list E = [1,2,1,4,5,4]
, and I want to extract the 2nd, 3rd and 5th element in E
, let A = [2,3,5]
, is there a faster way I can get the elements?假设我有列表
E = [1,2,1,4,5,4]
,我想提取E
中的第二、第三和第五个元素,让A = [2,3,5]
,有没有我可以更快地获取元素吗? I tried E[A]
but it doesn't work.我试过
E[A]
但它不起作用。 Thanks!谢谢!
Try this:尝试这个:
E = [1,2,1,4,5,4]
A = [2,3,5]
nE = [ E[a] for a in A ]
The itemgetter
function from the operator
module may do what you want:来自
operator
模块的itemgetter
function 可以做你想做的事:
from operator import itemgetter
E = [1,2,1,4,5,4]
A = [2,3,5]
print(itemgetter(*A)(E))
But you might need a different class altogether depending on the specifics of your speed needs.但是您可能需要完全不同的 class,具体取决于您的速度需求的具体情况。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.