![](/img/trans.png)
[英]How to remove element from list if element is present in list Python
[英]How to remove list with in a list if an element in one list is present in the other
我有一個包含幾個列表的列表。 如果兩個或多個列表具有公共元素,則列表可能包含0到9的整數元素,請刪除長度較小的列表
[[0, 3, 7],
[0, 3, 7, 9],
[0, 2, 3, 4, 7, 8, 9],
[2, 4, 8, 9],
[2, 4, 7, 8, 9],
[5, 6]]
輸出應為:
[[5, 6], [0, 2, 3, 4, 7, 8, 9]]
有任何想法嗎?
按長度對輸入列表進行排序,然后選擇最長的列表並將其添加到輸出中。 從最長的列表中創建一個集,以對其進行測試。 與該集合相交的任何后續較短列表都將被丟棄。
如果找到一個不相交的較短列表,請將其添加到輸出中,並更新您的基本集; 畢竟,現在相交的較短的列表與輸出中的一個或多個列表至少共享一個數字。 繼續直到所有列表都經過測試:
def eliminate_shorter(list_of_lists):
inputlist = sorted(list_of_lists, key=len)
outputlist = [inputlist.pop()]
numbers = set(outputlist[0])
for sublist in reversed(inputlist):
if not numbers.intersection(sublist):
numbers.update(sublist)
outputlist.append(sublist)
return outputlist
這是O(NlogN)復雜度的算法(由於初始排序)。
演示:
>>> sample = [[0, 3, 7], [0, 3, 7, 9], [0, 2, 3, 4, 7, 8, 9], [2, 4, 8, 9], [2, 4, 7, 8, 9], [5, 6]]
>>> def eliminate_shorter(list_of_lists):
... inputlist = sorted(list_of_lists, key=len)
... outputlist = [inputlist.pop()]
... numbers = set(outputlist[0])
... for sublist in reversed(inputlist):
... if not numbers.intersection(sublist):
... numbers.update(sublist)
... outputlist.append(sublist)
... return outputlist
...
>>> eliminate_shorter(sample)
[[0, 2, 3, 4, 7, 8, 9], [5, 6]]
l = [[0, 3, 7], [0, 3, 7, 9], [0, 2, 3, 4, 7, 8, 9], [2, 4, 8, 9], [2, 4, 7, 8, 9], [5, 6]]
longest = max(l,key=len)
st = set(longest)
print([longest]+[ele for ele in l if not st.intersection(ele)])
[[0, 2, 3, 4, 7, 8, 9], [5, 6]]
要捕獲重疊的子列表:
longest = max(l, key=len)
seen = set()
seen.update(longest)
out = [longest]
for sub in l:
if not seen.intersection(sub):
out.append(sub)
seen.update(sub)
選項1:每個列表元素的嵌套迭代,並相互比較。 (您知道了)。 可能不是最有效的方法。
選項2:將每個列表轉換(復制)為set
。 選擇最大的集合A
然后減去其他每個集合B
如果A - B
的結果的長度小於A
的長度,則丟棄B
表示的列表。 如果結果的長度與A
相同,則B
中的所有項目都是唯一的(不是A
所有項目),因此不要丟棄B
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.