【发布时间】:2022-11-22 14:26:47
【问题描述】:
正如标题所暗示的那样,如果我有一个包含键和值(其中这些值是集合)的字典,其中所有键的值都已经具有列表中的一个元素,他们将继续查看是否可以将下一个元素添加到放。
例如, lst = ['a', 'b', 'v']
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' 感到困惑
我正在考虑将列表变成一个类似于它被添加到的字典的字典,方法是将键变成值,将它们添加到一个集合中,如下所示: new_dct = {'a': {'test', 'letter', 'other}, 'b': : {'test', 'letter'}, 'v': set()}
但我不确定这是否只会使事情复杂化。
【问题讨论】:
标签: python python-3.x list set