如何在字典所有值集合含列表元素时跳过该元素并添加下一元素?
需求说明
我们需要处理一个值为集合的字典,处理规则如下:
- 遍历给定的元素列表
- 仅当字典中所有键对应的集合都已包含当前列表元素时,跳过该元素,尝试列表的下一个元素
- 将选中的元素添加到所有尚未包含它的集合中
示例
原始数据
lst = ['a', 'b', 'v'] sample_dct = {'test': {'a'}, 'letter': {'a'}, 'other': {'a'}} other_dct = {'test': {'a'}, 'letter': {'a'}, 'other': {'g'}} test_dct = {'test': {'a', 'b'}, 'letter': {'a', 'b'}, 'other': {'a'}}
处理后结果
sample_dct = {'test': {'a', 'b'}, 'letter': {'a', 'b'}, 'other': {'a', 'b'}} other_dct = {'test': {'a'}, 'letter': {'a'}, 'other': {'g', 'a'}} test_dct = {'test': {'a', 'b'}, 'letter': {'a', 'b'}, 'other': {'a', 'b'}}
我的尝试与问题
我尝试了以下代码:
lst = ['a', 'b', 'v'] other_dct = {'test': {'a'}, 'letter': {'a'}, 'other': {'g'}} j = 0 for i in other_dct: while not j == len(lst) - 1: if not lst[j] in other_dct[i]: x = other_dct[i] x.add(lst[j]) other_dct[i] = x break else: j += 1 j = 0 print(other_dct)
运行结果:{'test': {'b', 'a'}, 'letter': {'b', 'a'}, 'other': {'a', 'g'}}
目前代码只能实现给每个集合添加一次元素,但无法满足「只有当所有键的集合都包含'a'时,才给缺失的集合添加'b'」的逻辑。我考虑过将列表转换为类似{'a': {'test', 'letter', 'other'}, 'b': {'test', 'letter'}, 'v': set()}的结构,但不确定这种思路会不会让问题复杂化。
内容的提问来源于stack exchange,提问作者Polyaness
相关产品推荐
相关产品推荐

