您必须使用 freezeset 作为密钥。不能保证具有相同元素的集合总是会变成相同的repr
,或者tuple
因为集合是无序的。当然,除非您首先对集合元素进行排序,但这似乎很浪费
from collections import defaultdict
dataset = [('121', set(['NY'])), ('132', set(['CA', 'NY'])), ('198', set(['NY'])), ('676', set(['NY'])), ('89', set(['NY', 'CA']))]
output = defaultdict(list)
for value, key in dataset:
output[frozenset(key)].append(value)
或使用排序的元组
from collections import defaultdict
dataset = [('121', set(['NY'])), ('132', set(['CA', 'NY'])), ('198', set(['NY'])), ('676', set(['NY'])), ('89', set(['NY', 'CA']))]
output = defaultdict(list)
for value, key in dataset:
output[tuple(sorted(key))].append(value)
一个随机的例子来说明这一点
>>> s,t = set([736, 9753, 7126, 7907, 3350]), set([3350, 7907, 7126, 9753, 736])
>>> s == t
True
>>> tuple(s) == tuple(t)
False
>>> frozenset(s) == frozenset(t)
True
>>> hash(tuple(s)) == hash(tuple(t))
False
>>> hash(frozenset(s)) == hash(frozenset(t))
True