Filter the list of tuple lists

I have a list of tuple lists:

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 out any instance of "None":

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

The closest I came with this loop, but it does not discard the entire set (only "No"), and also destroys the list of lists of the tuple structure:

newList = []
for data in oldList:
    for point in data:
        newList.append(filter(None,point))
+4
source share
5 answers

The shortest way to do this is given the nested list:

>>> 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.

(, , 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)]]
+7

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

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

Tuple , . . , - 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

Source: https://habr.com/ru/post/1660229/


All Articles