2

次の配列があります。

[1 , 2]
[1 , 3]
[1 , 4]
[2 , 3]
[2 , 4]
[5 , 1]

次のような出力を印刷したい:

    "Items related to 1:"

        2, 3, 4, 5 *note this last one was on the first column and 1 in the second

    "Items related to 2:

        3, 4

    "Items related to 3:"
        1, 2

    "Items related to 4:"
        1, 2

    "Items related to 5:"
        1

何か案は?

4

3 に答える 3

4
def print_related(xs):
    d = {}
    for (a, b) in xs:
        d.setdefault(a, set()).add(b)
        d.setdefault(b, set()).add(a)
    for k in d:
        print "Items related to %s:" % k
        print "  " + repr(d[k])

これにより、サンプル入力が次のように出力されます

Items related to 1:
  set([2, 3, 4, 5])
Items related to 2:
  set([1, 3, 4])
Items related to 3:
  set([1, 2])
Items related to 4:
  set([1, 2])
Items related to 5:
  set([1])

セットを別の方法で印刷する代わりに独自の関数を使用reprしたり、繰り返しを気にする場合は別のデータ構造を使用したりできます。

以下の raymonad のコメントに従って、2 つの呼び出しdefaultdictを回避するために使用することもできます。setdefaultこの変更を行い、関連するアイテムのグループの望ましい表現を印刷するハックな方法を追加すると、

import collections

def print_related(xs):
    d = collections.defaultdict(set)
    for (a, b) in xs:
        d[a].add(b)
        d[b].add(a)
    for k in d:
        print "Items related to %s:" % k
        print "  " + repr(d[k])[5:-2]

グループを2, 3, 4, 5などとして出力します。

于 2013-06-02T23:20:39.890 に答える
1

これはトリックを行います:

L = [[1 , 2],
     [1 , 3],
     [1 , 4],
     [2 , 3],
     [2 , 4],
     [5 , 1]]

from collections import defaultdict

assoc = defaultdict(set)

for a, b in L:
    assoc[a].add(b)
    assoc[b].add(a)
for k, v in assoc.items():
    print(k, v)


1 {2, 3, 4, 5}
2 {1, 3, 4}
3 {1, 2}
4 {1, 2}
5 {1}
于 2013-06-02T23:25:33.787 に答える
0

キーが配列内の値であり、キーの値が関連する値のリストである辞書を使用することをお勧めします。

したがって、この場合は次のようになります。

{1: [2, 3, 4, 5], 
 2: [1, 3, 4],   # You missed `1` but it is related to `2`
 3: [1, 2],
 4: [1, 2],
 5: [1]}

これで、「関係」が冗長でないと仮定すると、これは簡単に生成できます。次のようなことができます:

  • リストを反復処理する:
  • 指定されたリスト内の要素を反復処理する:

  • 現在の要素がキーとして辞書にない場合は、それをキーとして追加し、他の値をキーの値として配列に追加します

  • 現在の要素がキーとして辞書にある場合は、ペアの他の要素をリストに追加します

これも、冗長な関係がない場合に機能します。冗長な関係がある場合はset、キーの値としてリストではなく、おそらく a が必要です。

于 2013-06-02T23:21:27.800 に答える