how to search item in list of list
Jussi Piitulainen
jussi.piitulainen at helsinki.fi
Mon Jun 13 01:13:43 EDT 2016
meInvent bbird writes:
> once a nested list have a word "node" then true else false
>
> def search(current_item):
> if isinstance(current_item, list):
> if len(current_item)==4:
> if [item for item in current_item if item[4] == "node"] != []:
> return True
> if True in [search(item) for item in current_item]:
> return True
> else:
> return False
>
> search(mresult)
>
> but it return false
Your mresult is not really nested in the way you are trying to treat it.
It looks like a list of lists of length 1, always containing a tuple of
length 5, where the last element is a string that may be 'node'. You
could just test each top-level item for item[0][4] == 'node'.
(It might help to make your case analysis more explicit. Now there's an
implicit return if current_item is not a list, and a fall-through to
another test if the length of current_item is 4. The structure of the
function should match the structure of the data.)
Below is the output of pprint.pprint(mresult). Much easier to read (also
less likely to break in transit - I had to fix an unfortunate line break
to make the original valid Python at all).
[[(2,
{'00': 0, '01': 1, '10': 1, '11': 1},
['000', '001', '010', '011', '100', '101', '110', '111'],
'xy',
'start')],
[(2,
{'00': 0, '01': 1, '10': 1, '11': 1},
['000', '001', '010', '011', '100', '101', '110', '111'],
'yz',
'start')],
[(2,
{'00': 0, '01': 1, '10': 1, '11': 1},
['000', '001', '010', '011', '100', '101 ', '110', '111'],
'xz',
'start')],
[(2,
{'00': 0, '01': 0, '10': 0, '11': 1},
['000', '001', '010', '011', '100', '101', '110', '111'],
'xy',
'start')],
[(2,
{' 11': 1, '00': 0, '01': 0, '10': 0},
['000', '001', '010', '011', '100', '101', ' 110', '111'],
'yz',
'start')],
[(2,
{'00': 0, '01': 0, '10': 0, '11': 1},
['000', '001', '010', '011', '100', '101', '110', '111'],
'xz',
'start')],
[(2,
{'00': 1, '01': 1, '10': 0, '11': 1},
['000', '001', '010', '011', '100', '101', '110', '111'],
'xy',
'start')],
[(2,
{'00': 1, '01': 1, '10': 0, '11': 1},
['000', '0 01', '010', '011', '100', '101', '110', '111'],
'yz',
'start')],
[(2,
{'00': 1, '01': 1, '10': 0, '11': 1},
['000', '001', '010', '011', '100', '101', '110', '1 11'],
'xz',
'start')],
[(1,
{'00': 0, '01': 1, '10': 1, '11': 1},
['00', '01', ' 11', '11', '10', '11', '11', '11'],
'xy',
'node')],
[(1,
{'00': 0, '01': 1, '10': 1, '11': 1},
['00', '01', '10', '11', '11', '11', '11', '11'],
'xy',
'node')],
[(1,
{'00': 0, '01': 1, '10': 1, '11': 1},
['00', '00', '10', '10', '10', '10', '11', '11'],
'xy',
'node')],
[(1,
{'00': 0, '01': 1, '10': 1, '11': 1},
['00', '00', '10', '11', '10', '10', '10', '11'],
'xy',
'node')],
[(1,
{'00': 0, '01': 1, '10': 1, '11': 1},
['00', '00', '10', '10', '10', '11', '10', '11'],
'xy',
'node')]]
More information about the Python-list
mailing list