繁体   English   中英

无论列表有多深,如何检查列表中的数据类型

[英]How to check what data types are in a list, no matter how deep the the list is

我有一个列表,无论列表有多深,我都想检查其中包含哪些数据类型。 我首先想到这样做:

all([isinstance(x, (int, float, str, bytes, list, tuple, set, dict)) for x in l])

但这似乎不起作用:

>>> l = [1, 2, 3, 4, [bytearray(b'1234')]]
>>> all([isinstance(x, (int, float, str, bytes, list, tuple, set, dict)) for x in l])
True

还有另一种方法可以做到这一点吗? 一个有效的?

您可以使用以下flatten function:

def flatten(s):
    for e in s:
        if isinstance(e, (tuple, list)):
            yield from flatten(e)
        else:
            yield e

l = [1, 2, 3, 4, [bytearray(b'1234')]]

result = all(isinstance(x, (int, float, str, bytes, list, tuple, set, dict)) for x in flatten(l))
print(result)

Output

False

这种方法的优点是您不必检查整个列表,如果找到False所有列表都会短路。

暂无
暂无

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

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