Python 访问列表的多个元素,知道它们的索引
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18272160/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Access multiple elements of list knowing their index
提问by hoang tran
I need to choose some elements from the given list, knowing their index. Let say I would like to create a new list, which contains element with index 1, 2, 5, from given list [-2, 1, 5, 3, 8, 5, 6]. What I did is:
我需要从给定的列表中选择一些元素,知道它们的索引。假设我想创建一个新列表,其中包含来自给定列表 [-2, 1, 5, 3, 8, 5, 6] 的索引为 1, 2, 5 的元素。我所做的是:
a = [-2,1,5,3,8,5,6]
b = [1,2,5]
c = [ a[i] for i in b]
Is there any better way to do it? something like c = a[b] ?
有没有更好的方法来做到这一点?像 c = a[b] 之类的东西?
采纳答案by TerryA
You can use operator.itemgetter
:
您可以使用operator.itemgetter
:
from operator import itemgetter
a = [-2, 1, 5, 3, 8, 5, 6]
b = [1, 2, 5]
print(itemgetter(*b)(a))
# Result:
(1, 5, 5)
Or you can use numpy:
或者你可以使用numpy:
import numpy as np
a = np.array([-2, 1, 5, 3, 8, 5, 6])
b = [1, 2, 5]
print(list(a[b]))
# Result:
[1, 5, 5]
But really, your current solution is fine. It's probably the neatest out of all of them.
但实际上,您当前的解决方案很好。它可能是所有这些中最整洁的。
回答by falsetru
Alternatives:
备择方案:
>>> map(a.__getitem__, b)
[1, 5, 5]
>>> import operator
>>> operator.itemgetter(*b)(a)
(1, 5, 5)
回答by Lavya 'Orion'
My answer does not use numpy or python collections.
我的答案不使用 numpy 或 python 集合。
One trivial way to find elements would be as follows:
查找元素的一种简单方法如下:
a = [-2, 1, 5, 3, 8, 5, 6]
b = [1, 2, 5]
c = [i for i in a if i in b]
Drawback: This method may not work for larger lists. Using numpy is recommended for larger lists.
缺点:此方法可能不适用于较大的列表。对于较大的列表,建议使用 numpy。
回答by Don Smythe
Basic and not very extensive testing comparing the execution time of the five supplied answers:
比较提供的五个答案的执行时间的基本而不是非常广泛的测试:
def numpyIndexValues(a, b):
na = np.array(a)
nb = np.array(b)
out = list(na[nb])
return out
def mapIndexValues(a, b):
out = map(a.__getitem__, b)
return list(out)
def getIndexValues(a, b):
out = operator.itemgetter(*b)(a)
return out
def pythonLoopOverlap(a, b):
c = [ a[i] for i in b]
return c
multipleListItemValues = lambda searchList, ind: [searchList[i] for i in ind]
using the following input:
使用以下输入:
a = range(0, 10000000)
b = range(500, 500000)
simple python loop was the quickest with lambda operation a close second, mapIndexValues and getIndexValues were consistently pretty similar with numpy method significantly slower after converting lists to numpy arrays.If data is already in numpy arrays the numpyIndexValues method with the numpy.array conversion removed is quickest.
简单的 python 循环是最快的,紧随其后的是 lambda 操作,mapIndexValues 和 getIndexValues 始终与 numpy 方法非常相似,在将列表转换为 numpy 数组后明显变慢。如果数据已经在 numpy 数组中,则删除 numpy.array 转换的 numpyIndexValues 方法是最快。
numpyIndexValues -> time:1.38940598 (when converted the lists to numpy arrays)
numpyIndexValues -> time:0.0193445 (using numpy array instead of python list as input, and conversion code removed)
mapIndexValues -> time:0.06477512099999999
getIndexValues -> time:0.06391049500000001
multipleListItemValues -> time:0.043773591
pythonLoopOverlap -> time:0.043021754999999995
回答by ecp
I'm sure this has already been considered: If the amount of indices in b is small and constant, one could just write the result like:
我确定这已经被考虑过:如果 b 中的索引数量很小且恒定,则可以将结果写为:
c = [a[b[0]]] + [a[b[1]]] + [a[b[2]]]
Or even simpler if the indices itself are constants...
或者更简单,如果索引本身是常量......
c = [a[1]] + [a[2]] + [a[5]]
Or if there is a consecutive range of indices...
或者,如果有一个连续的索引范围......
c = a[1:3] + [a[5]]
回答by BossaNova
Another solution could be via pandas Series:
另一种解决方案可能是通过熊猫系列:
import pandas as pd
a = pd.Series([-2, 1, 5, 3, 8, 5, 6])
b = [1, 2, 5]
c = a[b]
You can then convert c back to a list if you want:
如果需要,您可以将 c 转换回列表:
c = list(c)
回答by G M
Static indexes and small list?
静态索引和小列表?
Don't forget that if the list is small and the indexes don't change, as in your example, sometimes the best thing is to use sequence unpacking:
不要忘记,如果列表很小并且索引没有改变,如在您的示例中,有时最好的方法是使用序列解包:
_,a1,a2,_,_,a3,_ = a
The performance is much better and you can also save one line of code:
性能要好得多,还可以节省一行代码:
%timeit _,a1,b1,_,_,c1,_ = a
10000000 loops, best of 3: 154 ns per loop
%timeit itemgetter(*b)(a)
1000000 loops, best of 3: 753 ns per loop
%timeit [ a[i] for i in b]
1000000 loops, best of 3: 777 ns per loop
%timeit map(a.__getitem__, b)
1000000 loops, best of 3: 1.42 μs per loop
回答by Max Sirwa
Here's a simpler way:
这是一个更简单的方法:
a = [-2,1,5,3,8,5,6]
b = [1,2,5]
c = [e for i, e in enumerate(a) if i in b]
回答by Dmitry K. Chebanov
Kind of pythonic way:
一种pythonic方式:
c = [x for x in a if a.index(x) in b]