元组的所有行元素的同时条件

时间:2014-08-07 11:30:16

标签: python tuples

我有以下格式的元组:

[(None, datetime.datetime(2012, 9, 14, 15, 0)), (None, None),
 (None, None), (None, None), (None, datetime.datetime(2012, 9, 14, 16, 0))]

我想迭代元组,检查两个组件是否为空,如果是,则从项目中删除它们 - 只留下这些:

[(None, datetime.datetime(2012, 9, 14, 15, 0)),
 (None, datetime.datetime(2012, 9, 14, 16, 0))]

同时在单个循环中执行检查的最佳方法是什么?

3 个答案:

答案 0 :(得分:5)

output_list = filter(any, input_list)

答案 1 :(得分:1)

使用list comprehension和tuple unpacking:

>>> lst = [(None, datetime.datetime(2012, 9, 14, 15, 0)), (None, None),
... (None, None), (None, None), (None, datetime.datetime(2012, 9, 14, 16, 0))]
>>> [(a,b) for a,b in lst if a or b]
[(None, datetime.datetime(2012, 9, 14, 15, 0)),
 (None, datetime.datetime(2012, 9, 14, 16, 0))]

答案 2 :(得分:1)

我会使用列表理解和any()

left = [x for x in a if any(x)]
>> [(None, datetime.datetime(2012, 9, 14, 15, 0)), (None, datetime.datetime(2012, 9, 14, 16, 0))]