Skip to content Skip to sidebar Skip to footer

Check If Object Is List Of Lists Of Strings?

What is the elegant way to check if object is list of lists of strings, without nested loops? Probably here must be conventional ways to construct structured iterations. UPD Someth

Solution 1:

lol = [["a", "b"], ["c"], ["d", "e"], [1]]

from itertools import chain
printisinstance(lol, list) andall(isinstance(items, list) \
        andall(isinstance(item, str) for item in items) for items in lol)

Solution 2:

>>>lls = [ ["he","li"],["be","b"],["c","n","o"],["f","ne","na"] ]>>>isinstance(lls,list) andall([ all(isinstance(y,str) for y in x) andisinstance(x,list) for x in lls])
True
>>>not_lls = [ ["he","li"],["be",1]]>>>isinstance(lls,list) andall([ all(isinstance(y,str) for y in x) andisinstance(x,list) for x in not_lls])
False
>>>not_also_lls = [ ["he","li"],{}]>>>isinstance(lls,list) andall([ all(isinstance(y,str) for y in x) andisinstance(x,list) for x in not_also_lls])
False

Solution 3:

In a more generic way:

defvalidate(x, types):
    ifnotisinstance(x, types[0]):
        raise ValueError('expected %s got %s for %r' % (types[0], type(x), x))
    iflen(types) > 1:
        for y in x:
            validate(y, types[1:])

Usage:

try:
    validate(
        [['a', 'b', 'c'], ['d', 1], 3, ['e', 2, 'f']],
        [list, list, str])
except ValueError as e:
    print e  # expected <type 'str'> got <type 'int'> for 1try:
    validate(
        [['a', 'b', 'c'], ['d', 'X'], 3, ['e', 2, 'f']],
        [list, list, str])
except ValueError as e:
    print e # expected <type 'list'> got <type 'int'> for 3try:
    validate(
        [['a', 'b', 'c'], ['d', 'X'], ['3'], ['e', '2', 'f']],
        [list, list, str])
except ValueError as e:
    print e
else:
    print'ok'# ok

Solution 4:

Plain and straight forward:

defisListOfStrings(los):
  returnisinstance(los, list) andall(isinstance(e, str) for e in los)

defisListOfListOfStrings(lolos):
  returnisinstance(lolos, list) andall(isListOfStrings(los) for los in lolos)

print isListOfListOfStrings([["foo"]])

I can't recommend a recursion here because the test for the outer does not really resemble the test for the inner. Recursions are more useful if the depth of the recursion isn't fixed (as in this case) and the task is similar on each level (not the case here).

Post a Comment for "Check If Object Is List Of Lists Of Strings?"