过滤元组列表的列表

时间:2016-11-08 21:34:52

标签: python filter

我有一个元组列表列表:

oldList = [[(1,None),(2,45),(3,67)],[(1,None), (2,None), (3,None),(4,56),(5,78)],[(1, None),(2, 98)]]

我想过滤"无":

的任何实例
newList = [[(2,45),(3,67)], [(4,56),(5,78)], [(2, 98)]]

我最接近的是这个循环,但它不会丢弃整个元组(只有' None')并且它还会破坏元组结构列表列表:

newList = []
for data in oldList:
    for point in data:
        newList.append(filter(None,point))

5 个答案:

答案 0 :(得分:7)

执行此操作的最短方法是使用嵌套列表解析:

>>> newList = [[t for t in l if None not in t] for l in oldList]
>>> newList
[[(2, 45), (3, 67)], [(4, 56), (5, 78)], [(2, 98)]]

您需要嵌套两个列表推导,因为您正在处理列表列表。列表推导[[...] for l in oldList]的外部部分负责迭代所包含的每个内部列表的外部列表。然后在内部列表理解中你有[t for t in l if None not in t],这是一种非常简单的方式,表示你希望列表中的每个元组都不包含None

(可以说,您应该选择比lt更好的名称,但这取决于您的问题域。我选择了单字母名称来更好地突出显示代码。)

如果您对列表推导不熟悉或不舒服,这在逻辑上等同于以下内容:

>>> newList = []
>>> for l in oldList:
...     temp = []
...     for t in l:
...         if None not in t:
...             temp.append(t)
...     newList.append(temp)
...
>>> newList
[[(2, 45), (3, 67)], [(4, 56), (5, 78)], [(2, 98)]]

答案 1 :(得分:1)

您需要在第一个for循环中创建临时列表列表,以便将列表的嵌套结构维护为:

>>> new_list = []
>>> for sub_list in oldList:
...     temp_list = []
...     for item in sub_list:
...         if item[1] is not None:
...             temp_list.append(item)
...     new_list.append(temp_list)
...
>>> new_list
[[(2, 45), (3, 67)], [(4, 56), (5, 78)], [(2, 98)]]

或者,更好的方法是使用列表理解表达式

>>> oldList = [[(1,None),(2,45),(3,67)],[(1,None), (2,None), (3,None),(4,56),(5,78)],[(1, None),(2, 98)]]
>>> [[(k, v) for k, v in sub_list if v is not None ] for sub_list in oldList]
[[(2, 45), (3, 67)], [(4, 56), (5, 78)], [(2, 98)]]

答案 2 :(得分:0)

为什么不添加if块来检查元组point中的第一个元素是否存在或是True。你也可以使用列表理解,但我认为你是python的新手。

oldList = [[(1,None),(2,45),(3,67)],[(1,None), (2,None), (3,None),(4,56),(5,78)],[(1, None),(2, 98)]]

newList = []
for data in oldList:
    tempList = []
    for point in data:
        if point[1]:
            tempList.append(point)
    newList.append(tempList)

print newList
>>> [[(2, 45), (3, 67)], [(4, 56), (5, 78)], [(2, 98)]]

答案 3 :(得分:0)

元组是不可变的,因此您无法修改它们。你必须更换它们。到目前为止,最常规的方法是使用Python的列表理解:

>>> oldList = [[(1,None),(2,45),(3,67)],[(1,None), (2,None), (3,None),(4,56),(5,78)],[(1, None),(2, 98)]]
>>> [[tup for tup in sublist if not None in tup] for sublist in oldList]
[[(2, 45), (3, 67)], [(4, 56), (5, 78)], [(2, 98)]]
>>> 

答案 4 :(得分:0)

列表理解:

>>> newList = [[x for x in lst if None not in x] for lst in oldList]
>>> newList
[[(2, 45), (3, 67)], [(4, 56), (5, 78)], [(2, 98)]]
>>>