如何跳过没有列表中的元组?

时间:2014-09-04 06:36:31

标签: python list

我想过滤掉列表中仅包含None-elements的所有元组,所以这个列表

listobj = [(None, None, None, None), (None, None, None, None), (None, None, None, None),(None,None,'01/02/2015','25'),(None,None,'01/02/2015',None),(0,None,None,None)]

我想要那样的输出:

  listobj = [(None,None,'01/02/2015','25'),(None,None,'01/02/2015',None),(0,None,None,None)]

3 个答案:

答案 0 :(得分:6)

>>> [x for x in listobj if any(y is not None for y in x)]
[(None, None, '01/02/2015', '25'), (None, None, '01/02/2015', None), (0, None, None, None)]

答案 1 :(得分:2)

listobj= [i for i in listobj if i.count(None)<len(i)]

答案 2 :(得分:1)

不确定它是否必须是一个很酷的单线,但这是一个非常基本的方法:

def noneSeq(seq):
  """Helper function that determines if seq is all None."""
  for x in seq:
    if x is not None: return False
  return True

a = [x for x in listobj if not noneSeq(x)]

这给出了:

[(None, None, '01/02/2015', '25'), (None, None, '01/02/2015', None),
 (0, None, None, None)]