我需要通过列表计数

我有多个列表和一个大列表,我想检查大列表是否有我的一些小列表和计数,但我不想要冗余,例如:


list1 = [ "A" , "B" , "C" , "D"]

List2 = ['K' , "l" , "M"]


main_lists = [["A","C","K","L"] , ["B" , "C" , "M"]]


count1 = 0

count2 = 0

如果我在两个列表中的主列表中找到任何项目,我需要继续,我增加一个计数器但不是多余的,所以我的这种情况的输出应该是 count 1 = 2 count 2 = 2


我的列表中的A和C并不重要,只有其中1个会增加计数,我该怎么办


慕娘9325324
浏览 70回答 1
1回答

冉冉说

IIUC,您可以执行以下操作:list1 = ["A", "B", "C", "D"]list2 = ['K', "l", "M"]main_lists = [["A", "C", "K", "L"], ["B", "C", "M"]]set1 = set(list1)set2 = set(list2)count1 = sum(any(ie in set1 for ie in e) for e in main_lists)count2 = sum(any(ie in set2 for ie in e) for e in main_lists)print(count1)print(count2)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python