我有一个Python集
A = {34, 4, 7, 39, 40, 13, 18, 20}
和字典
B = {4: [6, 34, 39], 7: [18, 34], 13: [6, 18, 34], 18: [7, 13],
20: [31, 47], 34: [4, 7, 13], 39: [4, 8], 40: [15, 43]}
我想创建一个新的字典C,这样如果B中的任何值包含a中的数字,那么它们必须从相应的值列表中删除。键应该不受影响。
例如,我想要的输出是:
C = {4: [6], 7: [], 13: [6], 18: [], 20: [31, 47], 34: [], 39: [8]}
我试着用下面的代码来解决这个问题:
C = {}
for key, value in B_mod.items():
if value in A:
C[key] = value
print("C is:", C)
我得到的输出如下:
C is: {7: 18, 18: 7, 34: 4, 39: 4}
很明显,它不起作用。
*请注意,B_mod
意味着我正在使用代码取消字典B的值列表:
B_mod = {k:v[0] for k,v in B.items()} # Unlisitng the values of dictionary B
我这样做是因为我不能在b中迭代列表作为值。*
得到C有什么帮助吗?
您肯定可以在B
的值中遍历列表,实际上,您需要这样做,所以像这样:
>>> A = {34, 4, 7, 39, 40, 13, 18, 20}
>>> B = {4: [6, 34, 39], 7: [18, 34], 13: [6, 18, 34], 18: [7, 13], 20: [31, 47], 34: [4, 7, 13], 39: [4, 8], 40: [15, 43]}
>>> C = {}
>>> for key, value in B.items():
... new_value = []
... for val in value:
... if val not in A:
... new_value.append(val)
... C[key] = new_value
...
>>> C
{4: [6], 7: [], 13: [6], 18: [], 20: [31, 47], 34: [], 39: [8], 40: [15, 43]}
>>>
还可以将字典推导式与列表推导式结合使用:
>>> {k:[v for v in vs if v not in A] for k, vs in B.items()}
{4: [6], 7: [], 13: [6], 18: [], 20: [31, 47], 34: [], 39: [8], 40: [15, 43]}
相当于for循环方法。你觉得哪一个更有意义就哪一个。
可以同时使用字典和列表推导式:
>>> {k: [i for i in v if i not in A] for k, v in B.items()}
{4: [6], 7: [], 13: [6], 18: [], 20: [31, 47], 34: [], 39: [8], 40: [15, 43]}
您可以使用这个字典和列表推导式一行完成:
C = {k: [x for x in v if x not in A] for k, v in B.items()}