2016-11-08 138 views
4

我的元组列表的列表:过滤元组的列表的列表

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)]] 

我已经最接近来的是这个循环,但它不会删除整个元组(只“无”),它也破坏结构的元组的列表清单:

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

回答

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

你的东东d你先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)]] 
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)]] 
+0

这破坏了我想保留的结构。 – mk8efz

+0

@ mk8efz更新了我的答案。看看 –

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)]] 
>>> 
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)]] 
>>> 
+0

。你模仿;) –

+0

哈哈,我刚才看到还有其他评论xD –