How to check if all elements in a list of lists are strings

Suppose I have a list of lists of strings like this:

l=[['a','kl_hg', 'FOO'],['b', 'kl_c', 'po']]

      

Now I would like to use the command if

like this (in pseudocode!):

if allElementsOf(l).isString():
#do something

      

From this question, I learned how to check one variable if it is a string. So for one list, I could:

dummyL = ['a','kl_hg', 'FOO']
if all(isinstance(s, basestring) for s in dummyL):
#do something

      

and for my actual list, l

I could do:

if all(isinstance(el, basestring) for sl in l for el in sl):
#do something

      

Is there a way to do it, or is there a faster solution as it takes a while for huge lists of lists?

+3


source to share


4 answers


Your approach is correct, any short list of abbreviations looks slower . The fastest way is to use itertools :



import itertools
l=[['a','kl_hg', 'FOO'],['b', 'kl_c', 'po']]
if all( isinstance(x, basestring) for x in  itertools.chain.from_iterable(l) ):
    ...

      

+3


source


It's weird how someone said any () built-in function:

seq = [['a','kl_hg', 'FOO'], ['b', 'kl_c', 'po', 13]]

def all_string(_iterable):    
    return not any([not isinstance(n, basestring) for i in _iterable 
                        for n in i])

all_string(seq) # returns False

      



The advantage when using any () function is that it doesn't evaluate the entire sequence, it returns when the first true value is found - unlike all ().

+3


source


You probably want to use recursion to solve this problem in general for any nesting level. For example:

def all_strings(thing):
    if isinstance(thing, str):
        return True
    elif isinstance(thing, list):
        for subthing in thing:
            if not all_strings(subthing):
                return False
        return True
    else:
        return False

>>> print all_strings('foo')
True
>>> print all_strings(['foo'])
True
>>> print all_strings(['foo',['foo']])
True
>>> print all_strings(['foo',[1, 'foo']])
False
>>> 

      

+1


source


You can use this:

for x in l:
    for a in range(3):
        if type((x[a])) == str:
            print(x[a], ' is a string')

      

0


source







All Articles