2013-07-30 2 views
0

목록에서 여러 일치를 기반으로 사전을 만드는 데 문제가 있습니다. 내가 할 시도하고 무엇일치하는 값에 대한 사전을 작성하십시오.

items = [["1.pdf", "123", "train", "plaza"], 
     ["2.pdf","123", "plane", "town"], 
     ["3.pdf", "456", "train", "plaza"], 
     ["4.pdf", "123", "plane", "city"], 
     ["5.pdf", "123", "train", "plaza"], 
     ["6.pdf","123", "plane", "town"]] 

각 목록의 마지막 세 가지 항목에 일치하고 사전을 만들 : 여기

은 샘플 목록입니다.

그래서 위의 목록을 기반으로 원하는 출력을 것이라고 가정합니다.

{1 : [["1.pdf", "123", "train", "plaza"], 
     ["5.pdf", "123", "train", "plaza"]], 
2 : [["2.pdf","123", "plane", "town"], 
     ["6.pdf","123", "plane", "town"]] 
3 : [["3.pdf", "456", "train", "plaza"]] 
4 : [["4.pdf", "123", "plane", "city"]]} 
+1

는 당신이 우리를 보여줄 수있는 초기 시도를해야합니까? – sihrc

+0

왜 목록의 목록이 없습니까? 결국 키에 일련 번호를 사용하고 있습니다. –

+0

사전 키를 작성하는 데이터는 무엇입니까? – Howard

답변

7

다른 출력 데이터 형식을 제안 할 수 있습니까?

from collections import * 
d = defaultdict(list) 

for item in items: 
    d[tuple(item[1:])].append(item[0]) 

이 같은 딕셔너리 결과 :

{ 
    ('123', 'train', 'plaza'): ['1.pdf', '5.pdf'], 
    ('123', 'plane', 'town'): ['2.pdf', '6.pdf'], 
    ('123', 'plane', 'city'): ['4.pdf'], 
    ('456', 'train', 'plaza'): ['3.pdf'] 
} 
+0

나는이 방법을 좋아하고 일할 것이다. 그러나 색인이 순서대로 맞으면 어떻게 할 것인가? 예제 항목 [0], item [3], item [4] – thedemon

+0

그 질문이 맨 위 질문에 언급되지 않았다면 죄송합니다. – thedemon

1

잘못된 이름 지정 스키마는 무시하십시오.

items = [["1.pdf", "123", "train", "plaza"], 
     ["2.pdf","123", "plane", "town"], 
     ["3.pdf", "456", "train", "plaza"], 
     ["4.pdf", "123", "plane", "city"], 
     ["5.pdf", "123", "train", "plaza"], 
     ["6.pdf","123", "plane", "town"]] 

final = dict() 
for item in items: 
    final[tuple(item[1:])] = final.get(tuple(item[1:]),[]) + [item] 

new = dict() 
for i in range(len(final)): 
    new[i+1] = final.items()[i][1] 

for key,items in new.items(): 
    print key, ":\n",items 

수익률 (무작위로) :

{1 : [["1.pdf", "123", "train", "plaza"], 
     ["5.pdf", "123", "train", "plaza"]], 
2 : [["2.pdf","123", "plane", "town"], 
     ["6.pdf","123", "plane", "town"]] 
3 : [["3.pdf", "456", "train", "plaza"]] 
4 : [["4.pdf", "123", "plane", "city"]]} 
+1

튜플이 될 수 'str (item [1 :])'대신에 키를 사용하고'enumerate'는'range (len (final)) '보다 낫습니다. –

+0

일반 dict를 사용하면 출력 순서가 임의 일 수 있으므로 OP의 예상 출력과 일치하지 않습니다. –

1

당신은 collections.defaultdict 사용할 수 있습니다

>>> from collections import defaultdict 
>>> dic = defaultdict(list) 
for item in items: 
    dic[tuple(item[1:])].append(item) 
...  
>>> ans = { i: item for i, item in enumerate(dic.values(), 1)} 
>>> pprint(ans) 
{1: [['1.pdf', '123', 'train', 'plaza'], ['5.pdf', '123', 'train', 'plaza']], 
2: [['2.pdf', '123', 'plane', 'town'], ['6.pdf', '123', 'plane', 'town']], 
3: [['4.pdf', '123', 'plane', 'city']], 
4: [['3.pdf', '456', 'train', 'plaza']]} 

주문 사항은 다음 collections.OrderedDict 사용하는 경우 : 당신이 무엇을 찾고있다

>>> from collections import OrderedDict 
>>> dic = OrderedDict() 
for item in items:           
    dic.setdefault(tuple(item[1:]), []).append(item) 
...  
>>> ans = { i: item for i, item in enumerate(dic.values(), 1)} 
>>> pprint(ans) 
{1: [['1.pdf', '123', 'train', 'plaza'], ['5.pdf', '123', 'train', 'plaza']], 
2: [['2.pdf', '123', 'plane', 'town'], ['6.pdf', '123', 'plane', 'town']], 
3: [['3.pdf', '456', 'train', 'plaza']], 
4: [['4.pdf', '123', 'plane', 'city']]} 
1

을 나는 s groupby 작동. pandas :

In [2]: items 
Out[2]: 
[['1.pdf', '123', 'train', 'plaza'], 
['2.pdf', '123', 'plane', 'town'], 
['3.pdf', '456', 'train', 'plaza'], 
['4.pdf', '123', 'plane', 'city'], 
['5.pdf', '123', 'train', 'plaza'], 
['6.pdf', '123', 'plane', 'town']] 

In [3]: df = pd.DataFrame.from_records(items) 

In [4]: df 
Out[4]: 
     0 1  2  3 
0 1.pdf 123 train plaza 
1 2.pdf 123 plane town 
2 3.pdf 456 train plaza 
3 4.pdf 123 plane city 
4 5.pdf 123 train plaza 
5 6.pdf 123 plane town 


In [5]: for n, g in df.groupby([1, 2, 3]): 
    print "name", n 
    print g 
    ....:  
name ('123', 'plane', 'city') 
     0 1  2  3 
3 4.pdf 123 plane city 
name ('123', 'plane', 'town') 
     0 1  2  3 
1 2.pdf 123 plane town 
5 6.pdf 123 plane town 
name ('123', 'train', 'plaza') 
     0 1  2  3 
0 1.pdf 123 train plaza 
4 5.pdf 123 train plaza 
name ('456', 'train', 'plaza') 
     0 1  2  3 
2 3.pdf 456 train plaza 
관련 문제