【问题标题】:How do I go skip an element in a list if all the keys in a dictionary which has a value of a set already has that element?如果具有集合值的字典中的所有键都已经具有该元素,我该如何跳过列表中的元素?
【发布时间】: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


    【解决方案1】:

    您可以使用 python 的 all 函数来测试所有值是否都包含列表项。如果他们不这样做,那么该项目可以添加到所有值(因为它是一个集合重复并不重要)然后返回,否则移动到列表中的下一个字母。

    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'}}
    
    def add_items(items, dicts_set):
        for item in items:
            if not all((item in val for val in dicts_set.values())):
                for k in dicts_set:
                    dicts_set[k].add(item)
                return dicts_set
        return dicts_set
                
    print(add_items(lst, sample_dct))
    print(add_items(lst, other_dct))
    print(add_items(lst, test_dct))
    # output:
    #{'test': {'a', 'b'}, 'letter': {'a', 'b'}, 'other': {'a', 'b'}}
    #{'test': {'a'}, 'letter': {'a'}, 'other': {'g', 'a'}}
    #{'test': {'a', 'b'}, 'letter': {'a', 'b'}, 'other': {'a', 'b'}}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-02-15
      • 2017-10-17
      • 1970-01-01
      • 2018-12-20
      • 2018-12-08
      • 2012-09-21
      • 2018-04-08
      相关资源
      最近更新 更多