Python : 색인 세트를 기반으로 목록에서 하위 집합 선택
동일한 수의 항목이있는 여러 목록이 있습니다 (각각 개체 속성 지정).
property_a = [545., 656., 5.4, 33.]
property_b = [ 1.2, 1.3, 2.3, 0.3]
...
동일한 길이의 플래그가있는 목록
good_objects = [True, False, False, True]
(동등한 색인 목록으로 쉽게 대체 할 수 있습니다.
good_indices = [0, 3]
항목 또는 색인으로 표시된 값만 포함 하는 새 목록 property_asel
, property_bsel
... 을 생성하는 가장 쉬운 방법은 무엇입니까 True
?
property_asel = [545., 33.]
property_bsel = [ 1.2, 0.3]
목록 이해력을 사용할 수 있습니다 .
property_asel = [val for is_good, val in zip(good_objects, property_a) if is_good]
또는
property_asel = [property_a[i] for i in good_indices]
후자는 즉석에서 생성되는 대신 미리 계산된다는 가정하에 good_indices
의 길이보다 더 적기 때문에 더 빠릅니다 .property_a
good_indices
편집 : 첫 번째 옵션은 itertools.compress
Python 2.7 / 3.1부터 사용 가능한 것과 동일합니다 . @Gary Kerr 의 답변을 참조하십시오 .
property_asel = list(itertools.compress(good_objects, property_a))
두 가지 옵션이 있습니다.
numpy 사용 :
property_a = numpy.array([545., 656., 5.4, 33.]) property_b = numpy.array([ 1.2, 1.3, 2.3, 0.3]) good_objects = [True, False, False, True] good_indices = [0, 3] property_asel = property_a[good_objects] property_bsel = property_b[good_indices]
목록 이해력을 사용하여 압축합니다.
property_a = [545., 656., 5.4, 33.] property_b = [ 1.2, 1.3, 2.3, 0.3] good_objects = [True, False, False, True] good_indices = [0, 3] property_asel = [x for x, y in zip(property_a, good_objects) if y] property_bsel = [property_b[i] for i in good_indices]
내장 함수 zip 사용
property_asel = [a for (a, truth) in zip(property_a, good_objects) if truth]
편집하다
2.7의 새로운 기능을 살펴보십시오. 이제 위의 코드와 유사한 itertools 모듈에 함수가 있습니다.
http://docs.python.org/library/itertools.html#itertools.compress
itertools.compress('ABCDEF', [1,0,1,0,1,1]) =>
A, C, E, F
항목 목록과 참 / 필수 인덱스 목록 만 있다고 가정하면 이것이 가장 빠릅니다.
property_asel = [ property_a[index] for index in good_indices ]
즉, 속성 선택은 참 / 필수 인덱스가있는만큼만 라운드를 수행합니다. 단일 태그 (true / false) 목록의 규칙을 따르는 속성 목록이 많은 경우 동일한 목록 이해 원칙을 사용하여 인덱스 목록을 만들 수 있습니다.
good_indices = [ index for index, item in enumerate(good_objects) if item ]
이것은 good_objects의 각 항목을 반복하고 (열거 형으로 인덱스를 기억하면서) 항목이 참인 인덱스 만 반환합니다.
목록을 이해하지 못하는 사람을 위해 굵게 강조 표시된 코드가있는 영어 산문 버전이 있습니다.
대상 목록 에 대한 인덱스 의 모든 그룹 인덱스 항목의 존재 에 열거 의 좋은 객체 , 경우에 (어디)이 항목이 True를
Matlab 및 Scilab 언어는 질문에 대해 Python보다 더 간단하고 우아한 구문을 제공하므로 Python에서 Numpy 패키지를 사용하여 Matlab / Scilab을 모방하는 것이 최선이라고 생각합니다. 이렇게하면 문제에 대한 해결책이 매우 간결하고 우아합니다.
from numpy import *
property_a = array([545., 656., 5.4, 33.])
property_b = array([ 1.2, 1.3, 2.3, 0.3])
good_objects = [True, False, False, True]
good_indices = [0, 3]
property_asel = property_a[good_objects]
property_bsel = property_b[good_indices]
Numpy tries to mimic Matlab/Scilab but it comes at a cost: you need to declare every list with the keyword "array", something which will overload your script (this problem doesn't exist with Matlab/Scilab). Note that this solution is restricted to arrays of number, which is the case in your example.
참고URL : https://stackoverflow.com/questions/3179106/python-select-subset-from-list-based-on-index-set
'IT박스' 카테고리의 다른 글
LINQ to Entities에서 대량 삭제 (0) | 2020.10.10 |
---|---|
명령 줄에서 사용자의 잘리지 않은 Active Directory 그룹 가져 오기 (0) | 2020.10.10 |
mysql은 동일한 now ()로 여러 열을 업데이트합니다. (0) | 2020.10.10 |
node.js에서 병렬 실행 조정 (0) | 2020.10.10 |
PowerShell 탭 완성이 Bash처럼 작동하도록하는 방법 (0) | 2020.10.10 |