1

I have a list like the one below:

mylist = [[0, [1, 2]], [1, [1]], [2, [0, 2]], [3, [3]], [4, []], [5, []], [6, [0]]]

The inner list is [1, 2], [1], [0, 2] and so on.

The outer list is [0], [1], [2] and so on.

CASE 1: If the inner list has one item from myOtherlist and does not share this inner list with another number then get the outer item. Like the one below:

INPUT:

myOtherlist = [2, 3]

OUTPUT:

outer_item_list = [3]

CASE 2: If the inner list has all the items from myOtherlist then get the outer item and of course if one of the items from myOtherlist is on its own somewhere else in mylist. Like the one below:

INPUT:

myOtherlist = [0, 2]

OUTPUT:

outer_item_list = [2, 6]

CASE 3: If the inner list has one item from myOtherlist and it is on its own in the inner list then get the outer item. Like the one below:

INPUT:

myOtherlist = [0]

OUTPUT:

outer_item = [6]

MY CODE LOOKS LIKE THIS:

outer_item_list = []

for number in list:
    for inner in mylist:
        if number in inner[1] and len(inner[1]) == 1:
            fetch_outer_number = inner[0]
            outer_item_list.append(fetch_outer_number)
            print(outer_item_list)

I think I have managed to do CASE 3, but I need some help with CASE 1 and CASE 2.

NOTE: mylist is a common input for all 3 cases.

AlyssaAlex
  • 696
  • 2
  • 9
  • 33

1 Answers1

2

You can iterate over mylist and check if all of the elements in the second sublist are available in myOtherlist:

def find_items(mylist, myOtherlist):
    outer_item = []
    for x, y in mylist:
        if y and all(z in myOtherlist for z in y):
            outer_item.append(x)          
    return outer_item

Usage:

>>> mylist = [[0, [1, 2]], [1, [1]], [2, [0, 2]], [3, [3]], [4, []], [5, []], [6, [0]]]
>>> find_items(mylist, [2, 3])
[3]
>>> find_items(mylist, [0, 2])
[2, 6]
>>> find_items(mylist, [0])
[6]
Austin
  • 25,759
  • 4
  • 25
  • 48
  • +1 for the relevent use of a `if any and all` function: [How do Python's any and all functions work?](https://stackoverflow.com/questions/19389490/how-do-pythons-any-and-all-functions-work?answertab=votes#tab-top) – Basile Jun 05 '19 at 19:03