색인을 알고있는 목록의 여러 요소에 액세스
주어진 목록에서 색인을 알고 일부 요소를 선택해야합니다. 주어진 목록 [-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]
더 좋은 방법이 있습니까? c = a [b]와 같은 것?
당신은 사용할 수 있습니다 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)
또는 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]
그러나 실제로는 현재 솔루션이 좋습니다. 아마도 그들 중 가장 끔찍할 것입니다.
대안 :
>>> map(a.__getitem__, b)
[1, 5, 5]
>>> import operator
>>> operator.itemgetter(*b)(a)
(1, 5, 5)
또 다른 해결책은 pandas Series를 통한 것일 수 있습니다.
import pandas as pd
a = pd.Series([-2, 1, 5, 3, 8, 5, 6])
b = [1, 2, 5]
c = a[b]
원하는 경우 c를 목록으로 다시 변환 할 수 있습니다.
c = list(c)
제공된 다섯 가지 답변의 실행 시간을 비교하는 기본적이고 광범위하지 않은 테스트 :
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]
다음 입력을 사용하여 :
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.
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
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:
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]]
My answer does not use numpy or python collections.
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.
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
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]
참고URL : https://stackoverflow.com/questions/18272160/access-multiple-elements-of-list-knowing-their-index
'Programming' 카테고리의 다른 글
OData와 REST 웹 서비스의 차이점 (0) | 2020.05.12 |
---|---|
Babel 6은 기본값을 내보내는 방법을 변경합니다 (0) | 2020.05.12 |
Spark Standalone 클러스터의 작업자, 실행자, 코어 란 무엇입니까? (0) | 2020.05.12 |
Java에서 이중 물결표 (~~)의 의미는 무엇입니까? (0) | 2020.05.12 |
CSS / HTML : 텍스트를 이탤릭체로 만드는 올바른 방법은 무엇입니까? (0) | 2020.05.12 |