0

I have a list of lists, where each list contains some amount of words. Each list does not have to be the same length as every other list. Basically:

wordlist = [ ['cat', 'sheep', 'dog', 'pig', 'tomato'], ['apple', 'orange', 'sheep', 'dog' 'tomato'], ['cat', 'apple', 'sheep', 'tomato', 'dog'], ['garlic', 'tomato', 'dog' ]

I also have created a list of common words which can be found across all lists, for the above example, it would be:

common = ['sheep','dog', 'tomato']

I would like to now check, that for one list, if the common word appears in some order, in which other lists do those words show up in the same order. For example, in list1 the common words appear in the order ['sheep', 'dog'], and the same order appears in list2, so I should return:

list1: list2

In list3 ['tomato', 'dog'] appears in sequence, and it also does in list4, so these two get mapped. Making the total output as the following:

list1: list2
list2: list1
list3: list4
list4: list3

If list1 has common sublists in sequence with other lists, it would print as list1: list2, list5, list7 and so on. It should work for all sublists.

Is there a way of doing this?

FlameDra
  • 1,807
  • 7
  • 30
  • 47
  • Possible duplicate of [How to check a list contained by another list without a loop?](http://stackoverflow.com/questions/2582911/how-to-check-a-list-contained-by-another-list-without-a-loop) – WhatsThePoint Feb 01 '17 at 15:20
  • 1
    Does "common" contain words that appear in _all_ the lists? In that case, why is 'sheep' there? (It's not in the last list) – Jorge Plaza Feb 01 '17 at 15:50

1 Answers1

0

The solution depends on what values you expect from your lists.

If there is the possiblity of a repetition of a value, and you need to check that there is enough values in the tested container, then here is a time-inefficient solution:

def contained(candidate, container):
    temp = container[:]
    try:
        for v in candidate:
            temp.remove(v)
        return True
    except ValueError:
        return False

test this function with:

>>> a = [1,1,2,3]
>>> b = [1,2,3,4,5]
>>> contained(a,b)
False    
>>> a = [1,2,3]
>>> contained(a,b)
True
>>> a = [1,1,2,4,4]
>>> b = [1,1,2,2,2,3,4,4,5]
>>> contained(a,b)
True
greuze
  • 4,250
  • 5
  • 43
  • 62
Dev Jalla
  • 1,910
  • 2
  • 13
  • 21
  • There wont be repetitions. I'm only looking for the common words and the order they appear in mapping list to other lists where they appear in the same order. – FlameDra Feb 01 '17 at 15:42
  • Please provide the link from there you copied this answer: http://stackoverflow.com/questions/2582911/how-to-check-a-list-contained-by-another-list-without-a-loop – Dmitry Feb 01 '17 at 15:44
  • I get a AttributeError: 'str' object has no attribute 'remove' – FlameDra Feb 01 '17 at 20:15