[英]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)]]
我最接近的是這個循環,但它不會丟棄整個元組(只有'None'),它也會破壞元組結構列表的列表:
newList = []
for data in oldList:
for point in data:
newList.append(filter(None,point))
最簡單的方法是使用嵌套列表理解:
>>> 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)]]
您需要首先for
循環中創建一個臨時列表 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)]]
為什么不只是添加一個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)]]
元組是不可變的,因此您無法修改它們。 你必須更換它們。 到目前為止,最常規的方法是使用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)]]
>>>
列表理解:
>>> 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)]]
>>>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.