2016-11-08 90 views
4

我的元組列表的列表:過濾元組的列表的列表

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 = [] 
for data in oldList: 
    for point in data: 
     newList.append(filter(None,point)) 

回答

7

做到這一點,最簡單的辦法是用一個嵌套列表理解:

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

(按理說,你應該選擇比lt更好的名字,但是這將取決於你的問題域。我選擇的單字母域名更能凸顯代碼的結構)。

如果您不熟悉或與列表內涵不舒服,這是邏輯上等同於以下內容:

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

你的東東d你先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)]] 
0

爲什麼不只是添加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

這破壞了我想保留的結構。 – mk8efz

+0

@ mk8efz更新了我的答案。看看 –

0

元組是不可變的,因此你不能修改它們。你必須替換它們。到目前爲止,最規範的方式做到這一點,是利用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

。你模仿;) –

+0

哈哈,我剛纔看到還有其他評論xD –