2011-03-14 3 views
0
  • 두리스트 목록 h & i.
  • h [0]의 길이는 h [1]과 같고 h [2]와 같습니다. i [0], i [1], i [2]도 동일합니다.
  • h [0]의 길이가 i [0]과 같지 않을 수 있습니다.
  • h [0] [x] = i [0] [y] 일 때 "h [2] [x] & [2] [y]를 비교하십시오.
  • 기능이 "비교"는 다음과 같은 의미
    1. 분할 x.split ('\ n')에 및 y.split와 '\ 않음'을 발생리스트에 모두 X & Y ('\ n')에 .
    2. x.split ('\ n') 및 y.split ('\ n')의 각 요소에 대해 list_difference를 사용하여 중복을 제거하십시오.
    3. 그 결과를 새 목록 결과에 저장하십시오.

얻기다른 요소가 일치 할 때 목록의 중복 요소 제거 - 파이썬

def list_difference(list1, list2): 
    """Uses list1 as the reference, returns list of items not in list2.""" 
    diff_list = [] 
    for item in list1: 
     if not item in list2: 
      diff_list.append(item) 
    return diff_list 


h=[['match','meh'],['0','1'],['remove\n0\n12','1']] 
i=[['match','ignore0','ignore1'],['0','2','3'],['1\nremove','2','3']] 
result = result(h,i) 

# result should be: 
# result = [['match','meh'],['0','1'],['0','1']] 

# code not working: 
results = [] 
for l in h: 
    for p in i: 
     if l[0] == p[0]: 
      results.append(list_difference(l[2].split('\n'), p[2].split('\n'))) 

# Traceback (most recent call last): 
# File "<pyshell#19>", line 4, in <module> 
#  results.append(list_difference(l[2].split('\n'), p[2].split('\n'))) 
# IndexError: list index out of range 

아래 코드를 비 작동 가까이 :

이 작동하지만 아마도 가장 효율적인 또는 파이썬 코드가 아닙니다
for l0, l2 in h[0], h[2]: 
    for p0, p2 in i[0], i[2]: 
     if l0 == p0: 
      results.append(list_difference(l2.split('\n'), p2.split('\n'))) 
print results 
# [['h0_1']] 

답변

0

.

import string 
def list_difference(list1, list2): 
    """Uses list1 as the reference, returns list of items not in list2.""" 
    diff_list = [] 
    for item in list1: 
     if not item in list2: 
      diff_list.append(item) 
    return diff_list 

def list_in_list_newline_diff(h, i): 
    """When h[0] equals i[0], diffs h[2] against i[2], returns diff'd h.""" 
    new_h = [[],[],[]] 
    hh = zip(h[0], h[1], h[2]) 
    ii = zip(i[0], i[1], i[2]) 
    for hi, hd, hr in hh: 
     # print 'host %s\n%s' % (hi, hr.split('\n')) 
     for pi, pd, pr in ii: 
       if hi == pi: 
       #print 'prev %s\n%s' % (pi, pr.split('\n')) 
        hr = string.join(list_difference(hr.split('\n'), pr.split('\n')), sep='\n') 
     if hr == '': 
      continue 
     new_h[0].append(hi) 
     new_h[1].append(hd) 
     new_h[2].append(hr) 
    return new_h