检查列表中是否包含任何dict键


d = {('shot',): ['V'], ('I',): ['NP']}
s = ["I", "shot"]
s1 = ["I"]
s2 = ["shot"]
print(str(tuple(s,)))
print([i in d for i in tuple(s,)])
print(bool(set(tuple(s,)).intersection(d)))
print(d[tuple(s1,)])
print(d[tuple(s2,)])
for i in set(tuple(s,)).intersection(d):
print("Element "+i+" was found.")

假设我有一个像前面提到的dict,每个键都是一个元组。为什么会出现这样的结果:

('I', 'shot')
[False, False]
False
['NP']
['V']

取而代之的是:

('I', 'shot')
[True, True]
True
['NP']
['V']

Ishot都不是d中的键,因此两者都将是False。当您从列表中创建元组时,列表中的每个值都用于创建元组:

>>> tuple(["I", "shot"], )
('I', 'shot')

因此,当你在列表理解中迭代该列表时:

[i in d for i in tuple(s,)]

你有效地做的是:

for i in ('I', 'shot'):
if i in d:  # this will be 'I' in the first iteration, 'shot' in the next
...

由于Ishot本身都不是密钥,因此结果是False。字典中实际使用的键是元组,而不是字符串(这就是您最终要查找的(。

然而,您可能想要实现的是(因为tuple(s, )转换没有任何有用的作用(,查找一个将字符串作为字典中第一个元素的元组,而不是对其进行迭代:

>>> [(i, ) in d for i in s]
[True, True]

综上所述:

>>> 'I' in d
False
>>> 'shot' in d
False
>>> ('shot', ) in d
True
>>> ('I', ) in d
True

最后两个示例创建一个元组,然后检查该元组是否是字典中的键。

对键及其值的同样困惑也可能是set问题的原因,但您需要更明确地说明这一点——如果您想要一个迭代器,它只给您字典中的键,然后根据需要将两个集合相交,以实现您想要的目标,请使用d.keys()

相关内容

最新更新