2014-11-23 45 views
1

在我的情況下,重複項目不是重現在一個列表中的項目,而是在另一個列表中的相同位置中。例如:在少數列表中查找重複項目

list1 = [1,2,3,3,3,4,5,5] 
list2 = ['a','b','b','c','b','d','e','e'] 
list3 = ['T1','T2','T3','T4','T3','T4','T5','T5'] 

因此,所有3個列表中真正重複的位置是[2,4]和[6,7]。因爲在列表1中重複3,所以在列表2中'b'在與列表1相同的位置重複,列表3'T3'中。在第二種情況5中,e,T5表示其列表中相同位置的重複項目。我很難在一步中「自動」呈現結果。

1)我發現第一個列表

# Find Duplicated part numbers (exact maches) 
def list_duplicates(seq): 
    seen = set() 
    seen_add = seen.add 
    # adds all elements it doesn't know yet to seen and all other to seen_twice 
    seen_twice = set(x for x in seq if x in seen or seen_add(x)) 
    # turn the set into a list (as requested) 
    return list(seen_twice) 
# List of Duplicated part numbers 
D_list1 = list_duplicates(list1) 
D_list2 = list_duplicates(list2) 

2副本)然後我發現給出重複的位置,並期待在該位置在第二列表

# find the row position of duplicated part numbers 
def list_position_duplicates(list1,n,D_list1): 
    position = []  
    gen = (i for i,x in enumerate(data) if x == D_list1[n]) 
    for i in gen: position.append(i) 
    return position  

# Actual calculation find the row position of duplicated part numbers, beginning and end 
lpd_part = list_position_duplicates(list1,1,D_list1) 
start = lpd_part[0] 
end = lpd_part[-1] 

lpd_parent = list_position_duplicates(list2[start:end+1],0,D_list2) 

所以在步驟2中,我需要把n(在列表中找到重複的位置),我想自動執行此步驟,以在列表中的相同位置具有重複元素的位置。對於同一時間的所有重複,而不是一個一個「手動」。我認爲它只是需要一個for循環或如果,但我是Python的新手,我嘗試了很多組合,並沒有奏效。

回答

2

您可以使用同一個索引中所有3個列表中的項作爲鍵,並將相應的索引作爲值存儲在列表中。如果對於任何鍵存儲在列表中的索引超過1個,則它是重複的:

from itertools import izip 

def solve(*lists): 
    d = {} 
    for i, k in enumerate(izip(*lists)): 
    d.setdefault(k, []).append(i) 
    for k, v in d.items(): 
    if len(v) > 1: 
     print k, v 

solve(list1, list2, list3) 
#(3, 'b', 'T3') [2, 4] 
#(5, 'e', 'T5') [6, 7]