我有一个字典列表(LDICT)和一个字符串列表(LS)。我想检查一下,以确保LS中的项目不是LDICT中任何词典中的键。如果是这样,我想从LS中删除该项目。
我已经找到了一种用于for循环的方法,但这很丑陋,我正在努力了解如何使用列表理解来实现这一点。
有关使用for循环的示例,请参见下面的代码:
for item in LDICT:
for k, v in item.iteritems():
if k in LS:
LS.remove(k)
答案 0 :(得分:3)
使用any()
来检查LS
中的每个单词:
[k for k in LS if not any((k in t) for t in LDICT)]
答案 1 :(得分:1)
forbidden_keys = set(key for dct in LDICT for key in dct)
filtered_list = [item for item in LST if item not in forbidden_keys]
答案 2 :(得分:1)
创建LDICT
的所有格中的所有键的组合集,并从LS
的集合中减去:
(很远)
LDICT = [ {i:"" for i in range(k,k+20,3)} for k in range(0,100,20)]
LS = [x for x in range(100) if x%4 == 0]
print(LDICT)
print(LS)
all_keys = set(x for d in LDICT for x in d)
print(all_keys)
cleaned_keys = set(LS)-all_keys
print(cleaned_keys)
输出:
# LDICT
[{0: '', 3: '', 6: '', 9: '', 12: '', 15: '', 18: ''},
{20: '', 23: '', 26: '', 29: '', 32: '', 35: '', 38: ''},
{40: '', 43: '', 46: '', 49: '', 52: '', 55: '', 58: ''},
{60: '', 63: '', 66: '', 69: '', 72: '', 75: '', 78: ''},
{80: '', 83: '', 86: '', 89: '', 92: '', 95: '', 98: ''}]
# LS
[0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 52, 56, 60, 64,
68, 72, 76, 80, 84, 88, 92, 96]
# all_keys
{0, 3, 6, 9, 12, 15, 18, 20, 23, 26, 29, 32, 35, 38, 40, 43, 46, 49, 52, 55, 58, 60,
63, 66, 69, 72, 75, 78, 80, 83, 86, 89, 92, 95, 98}
# cleaned_keys
{64, 96, 4, 36, 68, 8, 44, 76, 16, 48, 84, 24, 56, 88, 28}
您只需要从cleaned_keys
中列出。
Doku: