2016-10-19 5 views
-2

나는이 문제로 2 일 동안 고생하고있어 도움이 필요하다. 목록 목록에서 반복되는 요소를 찾아야합니다. list_of_list = [(a1, b1, c1), (a2, b2, c2), ..., (an, bn, cn)] 여기서 "a"및 "b"요소는 정수이고 "c"요소는 부동 요소입니다.목록의 목록에서 반복되는 요소 찾기 python

예를 들어 a1 == a2 또는 a1 == bn 인 경우 전체 목록 요소로 새 목록을 만들어야하며 목록 목록의 모든 목록 (a, b, c)에 대해이 작업을 반복해야합니다. 다른 말로하면, 나는 하나 이상의리스트에 존재하는 요소를 가진 모든리스트가 필요하다. "a"와 "b"요소 만 비교해야하지만 최종 목록에서 관련 값 "c"를 가져와야합니다. 예를 들어

:

list_of_list = [(1, 2, 4.99), (3, 6, 5.99), (1, 4, 3.00), (5, 1, 1.12), (7, 8, 1.99) ] 

desired_result=[(1, 2, 4.99), (1, 4, 3.00), (5, 1, 1.12)] 

나는 많은 아이디어를 시도 ...하지만 좋은 아무것도가 오지 :

MI_network = [] #repeated elements list 
genesis = list(complete_net) #clon to work on 
genesis_next = list(genesis) #clon to remove elements in iterations 
genesis_next.remove(genesis_next[0]) 

while genesis_next != []: 
    for x in genesis: 
     if x[0] in genesis_next and x[1] not in genesis_next: 
      MI_network.append(x) 
     if x[0] not in genesis_next and x[1] in genesis_next: 
      MI_network.append(x) 
    genesis_next.remove(genesis_next[0]) 
+0

합니까 ', 또는 그것의 한 부분을? – ASGM

+0

'a1' 값과 만 비교해야합니까? –

+0

당신은 (1, n)에서 i, j에 대해'ai = aj'와'ai = bj'를 의미합니까? –

답변

-1

, 당신이 시도 할 수 있습니다 : 전체 결과를 포함 desired_result`

MI_network = [] 
complete_net = [(1, 2, 4.99), (3, 6, 5.99), (1, 4, 3.00), (5, 1, 1.12), (7, 8, 1.99)] 
genesis = list(complete_net) 

while genesis != []: 
    for x in genesis: 
     for gen in genesis: 
      if x[0] in gen and x[1] not in gen: 
       if x[0] != gen[2] and x[1] != gen[2]: 
        if x not in MI_network: 
         MI_network.append(x) 
      elif x[0] not in gen and x[1] in gen: 
       if x[0] != gen[2] and x[1] != gen[2]: 
        if x not in MI_network: 
         MI_network.append(x) 
      elif x[0] not in gen and x[1] not in gen: 
       pass 
    genesis.remove(genesis[0]) 

print(MI_network) 
[(1, 2, 4.99), (1, 4, 3.0), (5, 1, 1.12)] 
-1

을 그리고 이것은 내가 collections.defaultdict() 인식하지 때부터 어떻게 할 것입니다 . 당신의 아이디어를 사용

list_of_list = [(1, 2, 4.99), (3, 6, 5.99), (1, 4, 3.00), (5, 1, 1.12), (7, 8, 1.99) ] 
results = [] 
for i_sub, subset in enumerate(list_of_list): 
# test if ai == aj 
    rest = list_of_list[:i_sub] + list_of_list[i_sub + 1:] 
    if any(subset[0] == subrest[0] for subrest in rest): 
     results.append(subset) 
# test if ai == bj 
    elif any(subset[0] == subrest[1] for subrest in rest): 
     results.append(subset) 
# test if bi == aj 
    elif any(subset[1] == subrest[0] for subrest in rest): 
     results.append(subset) 
print(results) # -> [(1, 2, 4.99), (1, 4, 3.0), (5, 1, 1.12)] 
+0

감사합니다. 100 % 이해가 안되기 때문에이 코드를 "파산"하려고합니다. 그러나 순간에 그것은 정말로 잘 작동합니다. – K3rub

+0

이 방법을 @nicost와 비교하면 두 가지 결과가 달라집니다. nicost가 중복 목록을 제공하지만이 스크립트는 이러한 목록을 감지하지 못합니다. – K3rub

관련 문제