2

我有这个数据集。我想更新 MySQL 表。我可以以当前的形式做到这一点,但我认为转换为字典会缩小要更新的列表。

我的数据集:

dataset = [('121', set(['NY'])), ('132', set(['CA', 'NY'])), ('198', set(['NY'])), ('676', set(['NY'])), ('89', set(['NY', 'CA']))]

期望的输出:

一本字典 :

output = {'set(['NY'])':121,198,676, 'set(['CA', 'NY'])':132,89}
4

4 回答 4

5

必须使用 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
于 2012-06-05T22:41:38.287 回答
2

我认为您不能将 aset作为字典键,所以也许是元组?

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(key)].append(value)
    # or output[str(key)].append(value) if you want a string as the key
于 2012-06-05T22:20:33.247 回答
1

尝试这个:

dataset = [('121', set(['NY'])), ('132', set(['CA', 'NY'])), ('198', set(['NY'])), ('676', set(['NY'])), ('89', set(['NY', 'CA']))]
from collections import defaultdict
d = defaultdict(list)

for val, key in dataset:
    d[repr(key)].append(int(val))

d
> {"set(['NY', 'CA'])": [132, 89], "set(['NY'])": [121, 198, 676]}
于 2012-06-05T22:22:55.340 回答
1

这是一个替代方案defaultdict

dataset = [('121', set(['NY'])), ('132', set(['CA', 'NY'])), ('198', set(['NY'])), ('676', set(['NY'])), ('89', set(['NY', 'CA']))]    

output = {}
for value, key in dataset:
   output.setdefault(frozenset(key), []).append(value)

结果:

>>> output
{frozenset(['NY', 'CA']): ['132', '89'], frozenset(['NY']): ['121', '198', '676']}

由于以下行为,我更喜欢setdefault()在这里使用:defaultdict

>>> output = defaultdict(list, {frozenset(['NY', 'CA']): ['132', '89'], frozenset(['NY']): ['121', '198', '676']})
>>> output[frozenset(['FL'])]    # instead of a key error, this modifies output
[]
>>> output
defaultdict(<type 'list'>, {frozenset(['NY', 'CA']): ['132', '89'], frozenset(['FL']): [], frozenset(['NY']): ['121', '198', '676']})
于 2012-06-05T23:08:38.587 回答