2

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

Something like this:

l = [['a', 'b', 'c'], ['d', 1], 3, ['e', 2, 'f']]

def recurse(iterable, levels):
    results = []
    try:
        fn = levels[0]
    except IndexError:
        return
    for e in iterable:
        results.append(fn(e))
        try:
            results.extend(recurse(e, levels[1:]))
        except TypeError:
            pass
    return results

instance_of = lambda t: lambda e: isinstance(e, t)
print(recurse(l, [instance_of(list), instance_of(basestring)]))

UPD #2

Ive made some kind of homebrew functional programming, now it checks for list of lists of lists of strings:

from collections import Iterable
from itertools import imap, chain


def compose(f, g):
    return lambda *a, **kw: f(g(*a, **kw))

def concat(iterable):
    return chain.from_iterable(iterable)

def mk_iter(o):
    if isinstance(o, Iterable):
        return o
    else:
        return [o]

def put_in(f, g):
    """To support spirit of the Olympics :)"""
    return lambda e: concat(
        [mk_iter(f(e)),
         concat(imap(compose(mk_iter, g), mk_iter(e)))]
    )


ckr = lambda t: lambda e: isinstance(e, t)

l = [[['a', 'b'], ['c']], [['d'], ['1']], [1]]

fns = [ckr(list), ckr(list),ckr(list), ckr(str)]
fns.reverse()

print(list(reduce(lambda x, y: put_in(y, x), fns)(l)))
3
  • What counts as a nested loop for you? Commented Feb 12, 2014 at 9:51
  • The task's nature is to test everything in every element of a list. That's a nested loop on the logical level. Each attempt to do it otherwise (using chain or similar) will only lead to hiding that fact. Commented Feb 12, 2014 at 10:02
  • @JanneKarila everything with lots of for's and nesting :) Commented Feb 12, 2014 at 10:06

4 Answers 4

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

from itertools import chain
print isinstance(lol, list) and all(isinstance(items, list) \
        and all(isinstance(item, str) for item in items) for items in lol)
Sign up to request clarification or add additional context in comments.

1 Comment

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

3 Comments

@thefourtheye nice catch, added the check for main list also
he he he... Now compare this answer with my answer... :)
I'd prefer not to build useless lists, so just strip the []. And swap the check to avoid running into an error when testing [3]: isinstance(lls, list) and all(isinstance(x, list) and all(isinstance(y, str) for y in x) for x in lls)
1

In a more generic way:

def validate(x, types):
    if not isinstance(x, types[0]):
        raise ValueError('expected %s got %s for %r' % (types[0], type(x), x))
    if len(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 1
try:
    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 3

try:
    validate(
        [['a', 'b', 'c'], ['d', 'X'], ['3'], ['e', '2', 'f']],
        [list, list, str])
except ValueError as e:
    print e
else:
    print 'ok' # ok

Comments

0

Plain and straight forward:

def isListOfStrings(los):
  return isinstance(los, list) and all(isinstance(e, str) for e in los)

def isListOfListOfStrings(lolos):
  return isinstance(lolos, list) and all(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).

1 Comment

Try isListOfListOfStrings(1)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.