Skip to content Skip to sidebar Skip to footer

Python: Determine If An Unsorted List Is Contained In A 'list Of Lists', Regardless Of The Order To The Elements

I have a similar question to this question: Determine if 2 lists have the same elements, regardless of order? What is the best/quickest way to determine whether an unsorted list li

Solution 1:

You can use sets here:

defdoSomething(myListOfLists, otherInputs):
    s = set(otherInputs)           #create set from otherInputsfor item in myListOfLists: 
        #remove the common items between `s` and current sublist from `s`.
        s -= s.intersection(item) 
        #if `s` is empty, means all items found. Return Trueifnot s:                  
            returnTruereturnnotbool(s)
... >>> doSomething([[1, 2, 7],[6, 5, 4], [10, 9, 10]], [7, 6, 8])
False>>> doSomething([[1, 2, 7],[6, 5, 4], [10, 8, 10]], [7, 6, 8])
True

Update 1: Any Sublist contains exactly same items as otherInputs.

def doSomething(myListOfLists, otherInputs):
    s = set(otherInputs)
    return any(set(item) == s for item in myListOfLists)
... 
>>> doSomething([[6, 8, 7],[6, 5, 4], [10, 8, 10]], [7, 6, 8])
True
>>> doSomething([[1, 2, 7],[6, 5, 4], [10, 8, 10]], [7, 6, 8])
False

Update 2:otherInputs is a subset of any of the sublist:

def doSomething(myListOfLists, otherInputs):
    s = set(otherInputs)
    return any(s.issubset(item) for item in myListOfLists)
... 
>>> doSomething([[6, 8, 7],[6, 5, 4], [10, 8, 10]], [7, 6, 8])
True
>>> doSomething([[6, 8, 7, 10],[6, 5, 4], [10, 8, 10]], [7, 6, 8])
True
>>> doSomething([[1, 2, 7],[6, 5, 4], [10, 8, 10]], [7, 6, 8])
False

Solution 2:

Use sets

defdoSomething(myDictOfLists, otherInputs):

    list1 = []
    ...  # do something here with `otherInputs' 
    ...  # which gives `list1' some values# now only append `list1' to `myListOfLists' if it doesn't already exist# and if it does exist, remove it
    list1Set = set(list1)
    if list1Set notin myDictOfLists:
        myDictOfLists[list1Set] = list1

    return myDictOfLists

Solution 3:

If you sort given list and then append it to myListOfLists you can use this:

if sorted(list1) in myListOfLists:

Solution 4:

This algorithm appears to be slightly faster:

l1= [3, 4, 1, 2, 3]
l2= [4, 2, 3, 3, 1]
same=Truefor i in l1:if i not in l2:same=Falsebreak

For 1000000 loops, this takes 1.25399184227 sec on my computer, whilst

same = sorted(l1) == sorted(l2)

takes 1.9238319397 sec.

Post a Comment for "Python: Determine If An Unsorted List Is Contained In A 'list Of Lists', Regardless Of The Order To The Elements"