List problem

This is the place for queries that don't fit in any of the other categories.

List problem

Postby newprogrammer » Fri Apr 26, 2013 3:23 pm

Hello all,
how to find the list element that whether it is on other lists or not?
I know by the loop method (found= True). If you know better way please let me know. Thanks.
Example:
L1 = [1,2,3,4,5]
L2=[2,3,6]
L3=[1,6,8]
L4 = [3,10]

result: should print like this
1: L1,L3
2: L1,L2
3: L1,L2,L4
6: L2,L3
newprogrammer
 
Posts: 4
Joined: Mon Apr 22, 2013 5:18 pm

Re: List problem

Postby setrofim » Fri Apr 26, 2013 4:11 pm

Code: Select all
set(L1).intersection(set(L2))
setrofim
 
Posts: 288
Joined: Mon Mar 04, 2013 7:52 pm

Re: List problem

Postby Yoriz » Fri Apr 26, 2013 6:02 pm

Code: Select all
from collections import Counter


list1 = [1, 2, 3, 4, 5]
list2 = [2, 3, 6]
list3 = [1, 6, 8]
list4 = [3, 10]


def duplicateListsElements(*lists):
    counter = Counter()
    [counter.update(items) for items in lists]
    result = {}
    for index in counter.iterkeys():
        if counter[index] > 1:
            result[index] = [items for items in lists if index in items]
    return result

print duplicateListsElements(list1, list2, list3, list4)
{1: [[1, 2, 3, 4, 5], [1, 6, 8]], 2: [[1, 2, 3, 4, 5], [2, 3, 6]], 3: [[1, 2, 3, 4, 5], [2, 3, 6], [3, 10]], 6: [[2, 3, 6], [1, 6, 8]]}
New Users, Read This
Join the #python-forum IRC channel on irc.freenode.net!
Image
User avatar
Yoriz
 
Posts: 1178
Joined: Fri Feb 08, 2013 1:35 am
Location: UK


Return to General Coding Help

Who is online

Users browsing this forum: W3C [Linkcheck] and 3 guests