如何对这个python列表进行分组?
我有以下数组:如何对这个python列表进行分组?,python,arrays,list,Python,Arrays,List,我有以下数组: [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]
[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
有什么想法吗
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
调用。进行此更改并添加一种黑客方式来打印所需的相关项目组表示,结果是
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
等。我建议使用字典,其中键是数组中的值,键的值是相关值的列表
因此,在这种情况下,它看起来像:
{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]}
现在,假设“关系”不是多余的,这将很容易产生。你可以这样做:
- 在列表中迭代:
- 迭代给定列表中的元素:
- 如果当前元素不作为键在字典中,请将其作为键添加,并将另一个值作为键的值添加到数组中
- 如果当前元素作为键在字典中,则将该对中的另一个元素追加到列表中
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}
我更喜欢
d=defaultdict(set)
,这样就可以摆脱循环中的两个setdefault()
调用。