简体   繁体   English

如何检查列表列表中的所有元素是否为字符串

[英]How to check whether all elements in a list of lists are strings

Suppose I have a list of list of strings like this: 假设我有一个字符串列表,如下所示:

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

Now I would like to use an if command as follows (in pseudo-code!): 现在我想使用if命令如下(在伪代码中!):

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

From this question I learned how to check a single variable whether it is a string. 这个问题我学会了如何检查一个变量是否是一个字符串。 For a single list I could therefore do: 因此,对于单个列表,我可以这样做:

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

and for my actual list l I could then do: 和我的实际列表l我可以再做:

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

Is that the way to do it or is there a faster solution since that takes some time for huge lists of lists? 这是做到这一点的方式还是有更快的解决方案,因为这需要一些时间用于大量列表?

Your approach is right, any flatting list short cut seems slowest . 你的做法是正确的, 任何平局清单捷径似乎都是最慢的 A fastest way may be use itertools : 最快的方法可能是使用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) ):
    ...

It's odd how anyone has told 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 does not evaluate the whole sequence, it returns when the first True value is found - In contrast to all(). 使用any()函数时的优点是它不会评估整个序列,它会在找到第一个True值时返回 - 与all()相反。

You probably want to use recursion to solve this in the general case, for any level of nesting. 对于任何级别的嵌套,您可能希望在一般情况下使用递归来解决此问题。 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
>>> 

You can use this: 你可以用这个:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM