Test if tuple contains only None values with Python

匆匆过客 提交于 2019-12-10 18:56:04

问题


I need to find if my tuple contains only None value.

I use this code but i not sure it's the good practice:

# coding=utf8

def isOnlyNoneValuesTuple(t):
    """
    test if tuple contains only None values
    """
    if not len(tuple(itertools.ifilter(None, t))):
        return True
    else:
        return False

print isOnlyNoneValuesTuple((None,None,None,None,None,None,None,None,None,None,None,None,))
print isOnlyNoneValuesTuple((None,None,None,"val",None,None,None,None,))

Do you know other good practice to test it?

Thank you for your opinions


回答1:


return t.count(None) == len(t)

and it is faster than using all:

>>> setup = 't = [None, None]*100; t[1] = 1'
>>> timeit.timeit('all(item is None for item in t)', setup=setup)
0.8577961921691895
>>> timeit.timeit('t.count(None) == len(t)', setup=setup)
0.6855478286743164

and speed of all decreases according to index of not None element:

>>> setup = 't = [None, None]*100; t[100] = 1'
>>> timeit.timeit('all(item is None for item in t)', setup=setup)
8.18800687789917
>>> timeit.timeit('t.count(None) == len(t)', setup=setup)
0.698199987411499

BUT with big lists all is faster:

>>> setup = 't = [None, None]*10000; t[100] = 1'
>>> timeit.timeit('t.count(None) == len(t)', setup=setup)
47.24849891662598
>>> timeit.timeit('all(item is None for item in t)', setup=setup)
8.114514112472534

BUT not always though:

>>> setup = 't = [None, None]*10000; t[1000]=1'
>>> timeit.timeit('t.count(None) == len(t)', setup=setup)
47.475088119506836
>>> timeit.timeit('all(item is None for item in t)', setup=setup)
72.77452898025513

Conclusion that i make for myself about speed of all or count - very depends of data. If probability that you have all None in very big list - dont use all, it is very slow in that case.




回答2:


return all(item is None for item in t)



回答3:


return set(t) == {None}

Although I guess I'd use all() in practice.




回答4:


I second BrenBarn's answer, it's very Pythonic. But since you also asked about testing the code, I'll add my two cents.

You can create appropriate data structures by making use of the fact that Python allows you to multiply a list containing a single element by a factor n to get a list that contains the same element n times:

print(isOnlyNoneValuesTuple(tuple(10 * [None])))
print(isOnlyNoneValuesTuple(tuple(3 * [None] + ["val"] + 4 * [None])))


来源:https://stackoverflow.com/questions/21294383/test-if-tuple-contains-only-none-values-with-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!