过滤元组列表列表 [英] Filter 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)]]
我想过滤无"的任何实例:
newList = [[(2,45),(3,67)], [(4,56),(5,78)], [(2, 98)]]
我最接近的是这个循环,但它不会删除整个元组(只有无"),而且还会破坏元组结构列表:
newList = []对于 oldList 中的数据:对于数据点:newList.append(filter(None,point))
执行此操作的最短方法是使用嵌套列表推导式:
<预><代码>>>>newList = [[t for t in l if None not in t] for l in oldList]>>>新列表[[(2, 45), (3, 67)], [(4, 56), (5, 78)], [(2, 98)]]您需要嵌套两个列表推导式,因为您正在处理一个列表列表.列表推导式 [[...] for l in oldList]
的外部部分负责为包含的每个内部列表迭代外部列表.然后在内部列表理解中,您有 [t for t in l if None not in t]
,这是一种非常直接的方式,表示您希望列表中的每个元组不包含 无
.
(可以说,您应该选择比 l
和 t
更好的名称,但这取决于您的问题域.我选择了单字母名称以更好地突出显示代码的结构.)
如果您对列表推导式不熟悉或不舒服,这在逻辑上等同于以下内容:
<预><代码>>>>新列表 = []>>>对于 oldList 中的 l:... 温度 = []...对于 t in l:...如果 None 不在 t 中:... temp.append(t)... newList.append(temp)...>>>新列表[[(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屋!