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 的评论,您也可以使用defaultdict来避免这两个setdefault调用。进行此更改并添加一种 hacky 方式来打印相关项目组的所需表示会导致

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]}

现在,假设“关系”不是多余的,这将很容易生成。您可以执行以下操作:

  • 遍历列表:
  • 遍历给定列表中的元素:

  • 如果当前元素不在字典中作为键,则将其添加为键,并将其他值作为键的值添加到数组中

  • 如果当前元素在字典中作为键,则将该对中的另一个元素附加到列表中

如果您没有多余的关系,这同样有效。如果您确实有冗余关系,那么 aset可能是您想要的,而不是列表作为键的值。

于 2013-06-02T23:21:27.800 回答