2014-11-11 3 views
1

문제점 : 항목 쌍의 특정 속성을 비교하는 고유 항목 및 comparison_tool 목록이 있습니다.Python은 동시에 체크 된 항목을 제거하면서 동시에 항목 쌍을 순환합니다.

불필요한 비교없이 다른 항목에 대한 comparison_tool에 대해 1을 반환하는 모든 항목을 저장하려고합니다.

목록을 효율적으로 순환하는 방법이 있습니까? 내가 itertools.combinations 그것을 알아내는 시도 (list_of_items, 2) 또한 아래의 예와 실패

def comparison_tool(a, b): 
    '''Checks if prop matches (this is simplified for this example 
     and i can't break it out of this function) 
    ''' 
    if a.prop == b.prop: 
     return 1 # this is bad 
    else: 
     return 0 

list_of_items = [...] 
faulty_items = set()  
for a in list_of_items: 
    for b in list_of_items: 
     if comparison_tool(a,b): 
      faulty_items.add(a,b) 
      list_of_items.remove(b) 
      # Here is where i go wrong. I would like to remove 'b' from list_of_items 
      # so that 'a' doesn't cycle through 'b' in its upcoming loops 

또는 난 그냥 이것에 대해 잘못된 길로 갈거야?

+0

을 경우 싶어 사용하는 경우 comparison_tool (A, B)를 함수에서 True/False를 반환해야합니다. –

+0

정말로하고 싶은 것은 무엇입니까? '.prop'와 같은 값을 가지는 모든 아이템의 목록을 얻으시겠습니까? –

+0

예를 들어 : a.prop == b.prop으로'a'와'b'를 열거했습니다. 당신은 단지 "a", 그냥 "b"또는 둘 중 하나를 유지하고 싶습니까? –

답변

0

당신은 지능형리스트를 사용하여 수행해야합니다

newlist = [i for i in list_of_items if i.prop=1] 
0

좋은 값을 포함하는 새로운 목록을 작성하는 간단하다 :

list_of_items = [...] 
faulty_items = set() 
new_list = [] 
for i in list_of_items: 
    for j in new_list: 
     if comparison_tool(i, j): 
      faulty_items.add(i) 
      break 
    else: 
     new_list.append(i) 

list_of_items = new_list 
관련 문제