Python 筛选元组列表

Python 筛选元组列表,python,filter,Python,Filter,我有一个元组列表: oldList = [[(1,None),(2,45),(3,67)],[(1,None), (2,None), (3,None),(4,56),(5,78)],[(1, None),(2, 98)]] 我想筛选“无”的任何实例: 我遇到的最接近的循环是这个循环,但它不会删除整个元组(只有“None”),它还会破坏元组结构列表: newList = [] for data in oldList: for point in data: newList.

我有一个元组列表:

oldList = [[(1,None),(2,45),(3,67)],[(1,None), (2,None), (3,None),(4,56),(5,78)],[(1, None),(2, 98)]]
我想筛选“无”的任何实例:

我遇到的最接近的循环是这个循环,但它不会删除整个元组(只有“None”),它还会破坏元组结构列表:

newList = []
for data in oldList:
    for point in data:
        newList.append(filter(None,point))
您需要首先在
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)]]
或者,更好的方法是使用列表理解表达式,如下所示:


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

>>> 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)]]
>>> 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)]]
>>> 
您需要嵌套两个列表理解,因为您正在处理列表列表。列表的外部部分负责对包含的每个内部列表遍历外部列表。然后,在内部列表理解中,您有
[t表示t在l中,如果t中不包含任何元组]
,这是一种非常简单的方式,表示您希望列表中的每个元组都不包含
None

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

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

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

为什么不添加一个
if
块来检查元组
点中的第一个元素是否存在或是否为
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)]]

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

>>> 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)]]
>>> 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)]]
>>> 
列表理解:

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

这破坏了我试图保留的结构..你这个模仿者;)哈哈,我刚才看到还有其他评论xD