gpt4 book ai didi

list - 如何将包含集合的元组列表转换为字典?

转载 作者:行者123 更新时间:2023-11-28 20:09:21 25 4
gpt4 key购买 nike

我有这个数据集。我想更新 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}

最佳答案

必须为 key 使用卡住集。无法保证具有相同元素的集合将始终变成相同的 reprtuple,因为集合是无序的。当然,除非你首先对集合元素进行排序,但这看起来很浪费

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

关于list - 如何将包含集合的元组列表转换为字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10905758/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com