我有两个很长的列表,我知道较短的所有元素都包含在较长的列表中,但我需要隔离较长列表中不是较短的元素,以便我可以单独删除它们从字典中我得到了更长的清单。 到目前为止我所拥有的是:
for e in range(len(lst_ck)):
if lst_ck[e] not in lst_rk:
del currs[lst_ck[e]]
del lst_ck[e]
lst_ck
是较长的列表,lst_rk
是较短的列表,currs
是来自lst_ck
的字典。如果有帮助,它们都是来自词典的3位数字键列表。
答案 0 :(得分:4)
使用集合查找差异:
l1 = [1,2,3,4]
l2 = [1,2,3,4,6,7,8]
print(set(l2).difference(l1))
set([6, 7, 8]) # in l2 but not in l1
然后删除元素。
diff = set(l2).difference(l1):
your_list[:] = [ele for ele in your_list of ele not in diff]
如果列表非常大,您可能更喜欢生成器表达式:
your_list[:] = (ele for ele in your_list of ele not in diff)
答案 1 :(得分:2)
如果您不关心同一项目的多次出现,请使用set
。
diff = set(lst_ck) - set(lst_rk)
如果你在意,试试这个:
diff = [e for e in lst_rk if e not in lst_ck]