순회

2017-05-23 3 views
0

내 코드순회

PS를 수정하십시오 -

{'a':[1,4], 'b':2, 'c':3} 

답변

1

다음 방법 - 내가 좋아하는 것으로 출력을 필요

class Contact: 
    def __init__(self,cid, email): 
     self.cid=cid 
     self.email=email 
def ind(contacts): 
    index={} 
    #Code here 
    return index 
contacts = [Contact(1,'a'), 
     Contact(2,'b'), 
     Contact(3,'c'), 
     Contact(4,'a')] 
print(ind(contacts)) 

를 파이썬 비교적 새로운 해요 다음과 같은 목록 값을 만드십시오.

{'a':[1,4], 'b':[2], 'c':[3]} 

왜 이것이 좋지 않을지 상상할 수 없지만 특정 출력을 얻는 방법을 마지막에 추가했습니다.

이 이메일의 질서 유지하지 않습니다

def ind(contracts): 
    index={} 
    for contract in contracts: 
     index.setdefault(contract.email, []).append(contract.cid) 
    return index 

순서를 유지하려면 (예 : 'A'로 시작), 파일의 상단에 from collects import OrderedDict을 추가 한 다음 방법은 다음과 같습니다

def ind(contracts): 
    index = OrderedDict() 
    for contract in contracts: 
     index.setdefault(contract.email, []).append(contract.cid) 
    return index 

index의 인쇄물은 다르게 보일 것이지만, 보통 dict 개체 (주문과 함께)와 동일하게 작동합니다. (순서)와

정확한 출력 :

def ind(contracts): 
    index = OrderedDict() 
    for contract in contracts: 
     if contract.email in index: 
      value = index[contract.email] 
      if not isinstance(value, list): 
       index[contract.email] = [value] 
      index[contract.email].append(contract.cid) 
     else: 
      index[contract.email] = contract.cid 
    return index