2009-06-02 5 views
1

나는과 같이 사전의 목록을 가지고 :파이썬에서 사전 목록에서 특정 인덱스 항목의 목록을 가져 오기 (지능형리스트)

listDict = [{'id':1,'other':2},{'id':3,'other':4},{'id':5,'other':6}] 

는 내가 사전에서 모든 ID의 목록을합니다. 따라서 주어진 목록에서 목록을 얻습니다.

[1,3,5] 

한 줄이어야합니다. 나는 감사합니다 ... 난 그냥 구문을 잊어 버린 전에 이런 짓을 한 알 파이썬 괴짜

답변

10
>>> listDict = [{'id':1,'other':2},{'id':3,'other':4},{'id':5,'other':6}] 
>>> [item["id"] for item in listDict] 
[1, 3, 5] 
+0

정확히 내가 무엇을 찾고 있었습니까. 감사. –

+0

그리고 첫 번째 담당자에게 감사드립니다. :-)/me happy – balpha

0

[ELEM listDict에서 ELEM에 대한 [ 'ID']]

1

:

2

데이터의 크기에 따라 개념적으로 더 기쁘고 잠재적으로 더 빠른 방법입니다. 단순히 동일한 키를 사용하여 열 머리글 및 그룹 값으로 키를 참조하는 팬더 패키지를 사용

는 :

import pandas as pd 
listDict = [{'id':1,'other':2},{'id':3,'other':4},{'id':5,'other':6}] 
df = pd.DataFrame(listDict) 

# Then just reference the 'id' column to get a numpy array of it 
df['id'] 

# or just get a list 
df['id'].tolist() 

아래 일부 벤치마킹, 팬더는 분명 큰 데이터를 능가하는 성능. 작은 케이스는 주어진 3 개의 엔트리를 사용하며, 큰 케이스는 150k 엔트리를 가지고 있습니다 :

setup_large = "listDict = [];\ 
[listDict.extend(({'id':1,'other':2},{'id':3,'other':4},\ 
{'id':5,'other':6})) for _ in range(50000)];\ 
from operator import itemgetter;import pandas as pd;\ 
df = pd.DataFrame(listDict);" 

setup_small = "listDict = [];\ 
listDict.extend(({'id':1,'other':2},{'id':3,'other':4},{'id':5,'other':6}));\ 
from operator import itemgetter;import pandas as pd;\ 
df = pd.DataFrame(listDict);" 

method1 = '[item["id"] for item in listDict]' 
method2 = "df['id'].tolist()" 

import timeit 
t = timeit.Timer(method1, setup_small) 
print('Small Method LC: ' + str(t.timeit(100))) 
t = timeit.Timer(method2, setup_small) 
print('Small Method Pandas: ' + str(t.timeit(100))) 

t = timeit.Timer(method1, setup_large) 
print('Large Method LC: ' + str(t.timeit(100))) 
t = timeit.Timer(method2, setup_large) 
print('Large Method Pandas: ' + str(t.timeit(100))) 

#Small Method LC: 8.79764556885e-05 
#Small Method Pandas: 0.00153517723083 
#Large Method LC: 2.34853601456 
#Large Method Pandas: 0.605192184448 
+1

이런 식으로 판다를 사용하는 것은 과도한 일일 수 있습니다. 그러나 많은 데이터 조작을한다면 가치있는 것입니다. –

관련 문제