2
data_sets = [
    ['O'],
    ['X'],
    # These data sets put Sheet A in all possible locations and orientations
    # Data sets 2 - 9
    ['O', ['Sheet A', 'Location 1', 'Upright']],
    ['O', ['Sheet A', 'Location 2', 'Upright']],
    ['O', ['Sheet A', 'Location 3', 'Upright']],
    ['O', ['Sheet A', 'Location 4', 'Upright']],
    ['O', ['Sheet A', 'Location 1', 'Upside down']],
    ['O', ['Sheet A', 'Location 2', 'Upside down']],
    ['O', ['Sheet A', 'Location 3', 'Upside down']],
    ['O', ['Sheet A', 'Location 4', 'Upside down']]
    ]

for each in data_sets:
    if 'Sheet A' in each:
        print('1')

when i run this, it doesn't print anything because i dont think its going through all the sublists. how can i get this to work?

Brown Bear
  • 19,655
  • 10
  • 58
  • 76
wello man
  • 31
  • 4
  • You need to first check the length of your sublist then check for 'Sheet A' in possible sublists. – bhansa Sep 11 '17 at 09:08

4 Answers4

2

You can use itertools.chain.from_iterable

import itertools
for each in data_sets:
    if "Sheet A" in itertools.chain.from_iterable(eeach):
        print("1")

1
1
1
1
1
1
1
1

Here you have a live example

Netwave
  • 40,134
  • 6
  • 50
  • 93
  • Does the search look into comments? I would want to find this under "How to check items if in (inside) nested lists inside a list". Great tool, works. – Martin Zaske Oct 11 '18 at 21:24
  • I believe the interable(eeach) is a typo. For me, similar works with interable(each), exactly as in the "for"-line. – Martin Zaske Oct 11 '18 at 21:26
1

in is not recursive. It tries to find the item in the list itself. If the item is a list, in won't go down in the list to look for the string.

In your case, you could

  • check if the list has at least 2 items
  • perform in on the second item

like this:

for each in data_sets:
    if len(each)>1 and 'Sheet A' in each[1]:
        print('1')

of course if the structure is more complex/not fixed, you have to use a recursive approach which tests item type, like this: Python nested list recursion search

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
1
def listChecker(list_elems):
   for list_elem in list_elems:
      if "Sheet A" in list_elem:
         print "1"
      if any(isinstance(elem, list)  for elem in list_elem):
         listChecker(list_elem)

listChecker(data_sets)

you can also use this function. It will be helpful to print 1 in all cases of nested lists. Just pass your list object to this function.

P.Madhukar
  • 454
  • 3
  • 12
0

you can also check it by count.

for each in data_sets:
    if len(each)>1 and each[1].count("Sheet A"):
        print('1')
  • len(each)>1 checks the number of list item.
  • each[1] is the second sublist of your given list. and .count("Sheet A") returns occurrence number of Sheet A.
R.A.Munna
  • 1,699
  • 1
  • 15
  • 29