[英]Python list filtering: remove subsets from list of lists
如何使用Python如何通過有序子集匹配[[..],[..],..]
減少列表列表?
在該問題的上下文中,如果M
包含L
所有成員並且以相同的順序,則列表L是列表M
的子集 。 例如,列表[1,2]是列表[1,2,3]的子集,但不是列表[2,1,3]的子集。
輸入示例:
a. [[1, 2, 4, 8], [1, 2, 4, 5, 6], [1, 2, 3], [2, 3, 21], [1, 2, 3, 4], [1, 2, 3, 4, 5, 6, 7]]
b. [[2, 16, 17], [1, 2, 3, 4, 5, 6, 7], [1], [1, 2, 3, 4], [1, 2], [17, 18, 19, 22, 41, 48], [2, 3], [1, 2, 3], [50, 69], [1, 2, 3], [2, 3, 21], [1, 2, 3], [1, 2, 4, 8], [1, 2, 4, 5, 6]]
預期結果:
a. [[1, 2, 4, 8], [2, 3, 21], [1, 2, 3, 4, 5, 6, 7]]
b. [[2, 16, 17], [1, 2, 3, 4, 5, 6, 7], [17, 18, 19, 22, 41, 48], [50, 69], [2, 3, 21], [1, 2, 4, 8], [1, 2, 4, 5, 6]]
更多例子:
L = [[1, 2, 3, 4, 5, 6, 7], [1, 2, 5, 6]]
- 不減少
L = [[1, 2, 3, 4, 5, 6, 7],
, [1, 2, 3]
[1, 2, 4, 8]]
- 是減少
L = [[1, 2, 3, 4, 5, 6, 7], [7, 6, 5, 4, 3, 2, 1]]
- 不減少
(很抱歉導致與不正確的數據集混淆。)
這可以簡化,但是:
l = [[1, 2, 4, 8], [1, 2, 4, 5, 6], [1, 2, 3], [2, 3, 21], [1, 2, 3, 4], [1, 2, 3, 4, 5, 6, 7]]
l2 = l[:]
for m in l:
for n in l:
if set(m).issubset(set(n)) and m != n:
l2.remove(m)
break
print l2
[[1, 2, 4, 8], [2, 3, 21], [1, 2, 3, 4, 5, 6, 7]]
此代碼應該具有相當的內存效率。 除了存儲您的初始列表列表之外,此代碼使用可忽略的額外內存(不會創建臨時集或列表副本)。
def is_subset(needle,haystack):
""" Check if needle is ordered subset of haystack in O(n) """
if len(haystack) < len(needle): return False
index = 0
for element in needle:
try:
index = haystack.index(element, index) + 1
except ValueError:
return False
else:
return True
def filter_subsets(lists):
""" Given list of lists, return new list of lists without subsets """
for needle in lists:
if not any(is_subset(needle, haystack) for haystack in lists
if needle is not haystack):
yield needle
my_lists = [[1, 2, 4, 8], [1, 2, 4, 5, 6], [1, 2, 3],
[2, 3, 21], [1, 2, 3, 4], [1, 2, 3, 4, 5, 6, 7]]
print list(filter_subsets(my_lists))
>>> [[1, 2, 4, 8], [2, 3, 21], [1, 2, 3, 4, 5, 6, 7]]
而且,只是為了好玩,一個單行:
def filter_list(L):
return [x for x in L if not any(set(x)<=set(y) for y in L if x is not y)]
如果列表不是任何其他列表的子集,則列表是超級列表。 如果可以在另一個列表中按順序找到列表的每個元素,則它是另一個列表的子集。
這是我的代碼:
def is_sublist_of_any_list(cand, lists):
# Compare candidate to a single list
def is_sublist_of_list(cand, target):
try:
i = 0
for c in cand:
i = 1 + target.index(c, i)
return True
except ValueError:
return False
# See if candidate matches any other list
return any(is_sublist_of_list(cand, target) for target in lists if len(cand) <= len(target))
# Compare candidates to all other lists
def super_lists(lists):
return [cand for i, cand in enumerate(lists) if not is_sublist_of_any_list(cand, lists[:i] + lists[i+1:])]
if __name__ == '__main__':
lists = [[1, 2, 4, 8], [1, 2, 4, 5, 6], [1, 2, 3], [2, 3, 21], [1, 2, 3, 4], [1, 2, 3, 4, 5, 6, 7]]
superlists = super_lists(lists)
print superlists
結果如下:
[[1, 2, 4, 8], [2, 3, 21], [1, 2, 3, 4, 5, 6, 7]]
編輯:以后數據集的結果。
>>> lists = [[2, 16, 17], [1, 2, 3, 4, 5, 6, 7], [1], [1, 2, 3, 4], [1, 2], [17,
18, 19, 22, 41, 48], [2, 3], [1, 2, 3], [50, 69], [1, 2, 3], [2, 3, 21], [1, 2,
3], [1, 2, 4, 8], [1, 2, 4, 5, 6]]
>>> superlists = super_lists(lists)
>>> expected = [[2, 16, 17], [1, 2, 3, 4, 5, 6, 7], [17, 18, 19, 22, 41, 48], [5
0, 69], [2, 3, 21], [1, 2, 4, 8]]
>>> assert(superlists == expected)
>>> print superlists
[[2, 16, 17], [1, 2, 3, 4, 5, 6, 7], [17, 18, 19, 22, 41, 48], [50, 69], [2, 3,
21], [1, 2, 4, 8]]
編輯:我真的需要提高我的閱讀理解能力。 以下是實際問題的答案。 它利用了“ A is super of B
”意味着“ len(A) > len(B) or A == B
”的事實。
def advance_to(it, value):
"""Advances an iterator until it matches the given value. Returns False
if not found."""
for item in it:
if item == value:
return True
return False
def has_supersequence(seq, super_sequences):
"""Checks if the given sequence has a supersequence in the list of
supersequences."""
candidates = map(iter, super_sequences)
for next_item in seq:
candidates = [seq for seq in candidates if advance_to(seq, next_item)]
return len(candidates) > 0
def find_supersequences(sequences):
"""Finds the supersequences in the given list of sequences.
Sequence A is a supersequence of sequence B if B can be created by removing
items from A."""
super_seqs = []
for candidate in sorted(sequences, key=len, reverse=True):
if not has_supersequence(candidate, super_seqs):
super_seqs.append(candidate)
return super_seqs
print(find_supersequences([[1, 2, 4, 8], [1, 2, 4, 5, 6], [1, 2, 3],
[2, 3, 21], [1, 2, 3, 4], [1, 2, 3, 4, 5, 6, 7]]))
#Output: [[1, 2, 3, 4, 5, 6, 7], [1, 2, 4, 8], [2, 3, 21]]
如果您還需要保留序列的原始順序,則find_supersequences()
函數需要跟蹤序列的位置並在之后對輸出進行排序。
list0=[[1, 2, 4, 8], [1, 2, 4, 5, 6], [1, 2, 3], [2, 3, 21], [1, 2, 3, 4], [1, 2, 3, 4, 5, 6, 7]]
for list1 in list0[:]:
for list2 in list0:
if list2!=list1:
len1=len(list1)
c=0
for n in list2:
if n==list1[c]:
c+=1
if c==len1:
list0.remove(list1)
break
這會使用它的副本過濾list0。 如果預期結果與原始大小大致相同,那么這是很好的,只有少數“子集”要刪除。
如果預期結果很小並且原始文件很大,那么您可能更喜歡這個更友好的內存,因為它不會復制原始列表。
list0=[[1, 2, 4, 8], [1, 2, 4, 5, 6], [1, 2, 3], [2, 3, 21], [1, 2, 3, 4], [1, 2, 3, 4, 5, 6, 7]]
result=[]
for list1 in list0:
subset=False
for list2 in list0:
if list2!=list1:
len1=len(list1)
c=0
for n in list2:
if n==list1[c]:
c+=1
if c==len1:
subset=True
break
if subset:
break
if not subset:
result.append(list1)
這似乎有效:
original=[[1, 2, 4, 8], [1, 2, 4, 5, 6], [1, 2, 3], [2, 3, 21], [1, 2, 3, 4], [1, 2, 3, 4, 5, 6, 7]]
target=[[1, 2, 4, 8], [2, 3, 21], [1, 2, 3, 4, 5, 6, 7]]
class SetAndList:
def __init__(self,aList):
self.list=aList
self.set=set(aList)
self.isUnique=True
def compare(self,aList):
s=set(aList)
if self.set.issubset(s):
#print self.list,'superceded by',aList
self.isUnique=False
def listReduce(lists):
temp=[]
for l in lists:
for t in temp:
t.compare(l)
temp.append( SetAndList(l) )
return [t.list for t in temp if t.isUnique]
print listReduce(original)
print target
這將打印計算列表和目標以進行視覺比較。
在比較方法中取消注釋打印行,以查看各種列表如何被取代。
用python 2.6.2測試
我實現了一個不同的issubseq
因為你沒有說[1, 2, 4, 5, 6]
issubseq
[1, 2, 4, 5, 6]
是[1, 2, 3, 4, 5, 6, 7]
[1, 2, 4, 5, 6]
的子序列,例如(除了痛苦的慢) )。 我想出的解決方案如下:
def is_subseq(a, b):
if len(a) > len(b): return False
start = 0
for el in a:
while start < len(b):
if el == b[start]:
break
start = start + 1
else:
return False
return True
def filter_partial_matches(sets):
return [s for s in sets if all([not(is_subseq(s, ss)) for ss in sets if s != ss])]
一個簡單的測試用例,給出您的輸入和輸出:
>>> test = [[1, 2, 4, 8], [1, 2, 4, 5, 6], [1, 2, 3], [2, 3, 21], [1, 2, 3, 4], [1, 2, 3, 4, 5, 6, 7]]
>>> another_test = [[1, 2, 3, 4], [2, 4, 3], [3, 4, 5]]
>>> filter_partial_matches(test)
[[1, 2, 4, 8], [2, 3, 21], [1, 2, 3, 4, 5, 6, 7]]
>>> filter_partial_matches(another_test)
[[1, 2, 3, 4], [2, 4, 3], [3, 4, 5]]
希望能幫助到你!
新測試案例后的精致答案:
original= [[2, 16, 17], [1, 2, 3, 4, 5, 6, 7], [1], [1, 2, 3, 4], [1, 2], [17, 18, 19, 22, 41, 48], [2, 3], [1, 2, 3], [50, 69], [1, 2, 3], [2, 3, 21], [1, 2, 3], [1, 2, 4, 8], [1, 2, 4, 5, 6]]
class SetAndList:
def __init__(self,aList):
self.list=aList
self.set=set(aList)
self.isUnique=True
def compare(self,other):
if self.set.issubset(other.set):
#print self.list,'superceded by',other.list
self.isUnique=False
def listReduce(lists):
temp=[]
for l in lists:
s=SetAndList(l)
for t in temp:
t.compare(s)
s.compare(t)
temp.append( s )
temp=[t for t in temp if t.isUnique]
return [t.list for t in temp if t.isUnique]
print listReduce(original)
你沒有提供所需的輸出,但我猜這是對的,因為[1,2,3]
沒有出現在輸出中。
感謝所有建議解決方案和處理我有時錯誤的數據集的人。 使用@hughdbrown解決方案我將其修改為我想要的:
修改是在目標上使用滑動窗口以確保找到子集序列。 我想我應該使用一個比“Set”更合適的詞來描述我的問題。
def is_sublist_of_any_list(cand, lists):
# Compare candidate to a single list
def is_sublist_of_list(cand, target):
try:
i = 0
try:
start = target.index(cand[0])
except:
return False
while start < (len(target) + len(cand)) - start:
if cand == target[start:len(cand)]:
return True
else:
start = target.index(cand[0], start + 1)
except ValueError:
return False
# See if candidate matches any other list
return any(is_sublist_of_list(cand, target) for target in lists if len(cand) <= len(target))
# Compare candidates to all other lists
def super_lists(lists):
a = [cand for i, cand in enumerate(lists) if not is_sublist_of_any_list(cand, lists[:i] + lists[i+1:])]
return a
lists = [[2, 16, 17], [1, 2, 3, 4, 5, 6, 7], [1], [1, 2, 3, 4], [1, 2], [17, 18, 19, 22, 41, 48], [2, 3], [1, 2, 3], [50, 69], [1, 2, 3], [2, 3, 21], [1, 2, 3], [1, 2, 4, 8], [1, 2, 4, 5, 6]]
expect = [[2, 16, 17], [1, 2, 3, 4, 5, 6, 7], [17, 18, 19, 22, 41, 48], [50, 69], [2, 3, 21], [1, 2, 4, 8], [1, 2, 4, 5, 6]]
def test():
out = super_lists(list(lists))
print "In : ", lists
print "Out : ", out
assert (out == expect)
結果:
In : [[2, 16, 17], [1, 2, 3, 4, 5, 6, 7], [1], [1, 2, 3, 4], [1, 2], [17, 18, 19, 22, 41, 48], [2, 3], [1, 2, 3], [50, 69], [1, 2, 3], [2, 3, 21], [1, 2, 3], [1, 2, 4, 8], [1, 2, 4, 5, 6]]
Out : [[2, 16, 17], [1, 2, 3, 4, 5, 6, 7], [17, 18, 19, 22, 41, 48], [50, 69], [2, 3, 21], [1, 2, 4, 8], [1, 2, 4, 5, 6]]
所以你真正想要的是知道一個列表是否是一個子字符串,可以說是另一個,所有匹配的元素是連續的。 下面是將候選列表和目標列表轉換為逗號分隔字符串並執行子字符串比較以查看候選項是否出現在目標列表中的代碼
def is_sublist_of_any_list(cand, lists):
def comma_list(l):
return "," + ",".join(str(x) for x in l) + ","
cand = comma_list(cand)
return any(cand in comma_list(target) for target in lists if len(cand) <= len(target))
def super_lists(lists):
return [cand for i, cand in enumerate(lists) if not is_sublist_of_any_list(cand, lists[:i] + lists[i+1:])]
函數comma_list()在列表中放置前導和尾隨逗號,以確保整數是完全分隔的。 否則,[1]將是[100]的子集,例如。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.