0

リスト[[1、2、7]、[1、2、3]、[1、2、3、7]、[1、2、3、5、6、7]]があり、[1 、2,3,7]最終結果として(これは一種のリバースエンジニアリングです)。1つのロジックは交差点をチェックすることです-

 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つの最終的な答えにつながる項目がさらにある可能性があります。しかし、今のところ、[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

2つのリスト要素の最大の交点を見つけようとしているようです。これはそれを行います:

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 に答える