I have a list I would like to check what data types are in it, no matter how many levels deep the list goes. I first thought to do this:
all([isinstance(x, (int, float, str, bytes, list, tuple, set, dict)) for x in l])
But it doesn't seem to work:
>>> l = [1, 2, 3, 4, [bytearray(b'1234')]]
>>> all([isinstance(x, (int, float, str, bytes, list, tuple, set, dict)) for x in l])
True
Is there another method to do this? One that works?
You could use the following 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
The advantage of this approach is that you wont have to check the entire list, all will short-circuit if it finds a False
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.