筛选元组列表 [英] Filter a list of lists of tuples

查看:157
本文介绍了筛选元组列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我想筛选任何None的实例:

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

最接近的就是这个循环,它不会删除整个元组(只有'None'),它也会销毁元组结构列表:

  newList = [] 
用于oldList中的数据:
用于数据中的点:$ b​​ $ b newList.append(filter(None,point))
pre

解决方案

最简单的方法是使用嵌套的列表解析:

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


$ b

您需要嵌套两个列表解析,因为您正在处理列表列表。列表理解的外部部分 [[...] for oldList] 负责遍历包含的每个内部列表的外部列表。然后在内部列表理解中,你有 [t for t in l if None not in t] ,这是一个非常简单的说法,希望列表中的每个元组不包含 None



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

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

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


I have a list of lists of tuples:

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

I would like to filter any instance of "None":

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

The closest I've come is with this loop, but it does not drop the entire tuple (only the 'None') and it also destroys the list of lists of tuples structure:

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

解决方案

The shortest way to do this is with a nested list comprehension:

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

You need to nest two list comprehensions because you are dealing with a list of lists. The outer part of the list comprehension [[...] for l in oldList] takes care of iterating through the outer list for each inner list contained. Then inside the inner list comprehension you have [t for t in l if None not in t], which is a pretty straightforward way of saying you want each tuple in the list which does not contain a None.

(Arguably, you should choose better names than l and t, but that would depend on your problem domain. I've chosen single-letter names to better highlight the structure of the code.)

If you are unfamiliar or uncomfortable with list comprehensions, this is logically equivalent to the following:

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

这篇关于筛选元组列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆