0

我有一个列表 [[1, 2, 7], [1, 2, 3], [1, 2, 3, 7], [1, 2, 3, 5, 6, 7]] 我需要 [1 ,2,3,7] 作为最终结果(这是一种逆向工程)。一种逻辑是检查交叉点 -

 while(i<dlistlen):
  j=i+1
  while(j<dlistlen):
   il = dlist1[i]
   jl = dlist1[j]

   tmp = list(set(il) & set(jl))
   print tmp 

  #print i,j
   j=j+1 
  i=i+1

这给了我输出:

[1, 2]
[1, 2, 7]
[1, 2, 7]
[1, 2, 3]
[1, 2, 3]
[1, 2, 3, 7]
[]

看起来我接近 [1,2,3,7] 作为我的最终答案,但不知道如何。请注意,在第一个列表中 (([[1, 2, 7], [1, 2, 3], [1, 2, 3, 7], [1, 2, 3, 5, 6, 7] ] )) 除了 [1,2,3,4] 之外,可能还有更多的项目导致更多的最终答案。但截至目前,我只需要提取 [1,2,3,7] 。请注意,这不是作业,我正在创建适合我需要的自己的聚类算法。

4

2 回答 2

2

您可以使用Counter类来跟踪元素出现的频率。

>>> from itertools import chain
>>> from collections import Counter
>>> l =  [[1, 2, 7], [1, 2, 3], [1, 2, 3, 7], [1, 2, 3, 5, 6, 7]]
>>> #use chain(*l) to flatten the lists into a single list
>>> c = Counter(chain(*l))
>>> print c
Counter({1: 4, 2: 4, 3: 3, 7: 3, 5: 1, 6: 1})
>>> #sort keys in order of descending frequency
>>> sortedValues = sorted(c.keys(), key=lambda x: c[x], reverse=True)
>>> #show the four most common values
>>> print sortedValues[:4]
[1, 2, 3, 7]
>>> #alternatively, show the values that appear in more than 50% of all lists
>>> print [value for value, freq in c.iteritems() if float(freq) / len(l) > 0.50]
[1, 2, 3, 7]
于 2013-03-26T11:59:44.043 回答
1

看起来您正试图找到两个列表元素的最大交集。这将做到这一点:

from itertools import combinations

# convert all list elements to sets for speed
dlist = [set(x) for x in dlist]

intersections = (x & y for x, y in combinations(dlist, 2))
longest_intersection = max(intersections, key=len)
于 2013-03-26T12:06:27.967 回答