Skip to main content
 首页 » 编程设计

Python之在列表列表中查找元组

2025年05月04日15myhome

我有元组列表 (mytu​​ples) 和列表列表 (mylist)。

我想找出 mytuples 中的每个元组在每个列表中出现的次数。

假设元组 (2,3) 出现在 [1,2,3,4], [2,3,4,5] 和 [2,3]。因此 (2,3) 的计数是 3。

元组和列表的大小可以不同。

mytuples = [(2,3), (3,6), (1,2)] 
mylist = [[1,2,3,4],[2,3,4,5],[2,3],[4,5,6]] 
 
count={}     
for m in mytuples : 
    counter = 0         
    for i in mylist : 
        if set(m).issubset(i): 
            counter = counter + 1 
    count[m]=counter 

我的输出是 {(2,3):3, (3,6): 0, (1,2):1}

这种方法工作正常,但当我的列表很大时,比如 1000 条记录,它会更耗时。这可以更快地完成吗?有什么建议吗?

请您参考如下方法:

使用字典理解,我们可以将所有内容简化为一行。

假设元组总是成对的:

count = {(x,y):sum((x in i and y in i) for i in mylist) for x,y in mytuples} 
# {(1, 2): 1, (2, 3): 3, (3, 6): 0} 

或者如果元组大小未知,您可以使用 all() 求和:

count = {t:sum(all(x in i for x in t) for i in mylist) for t in mytuples} 
# {(1, 2): 1, (2, 3): 3, (3, 6): 0} 

如果不清楚:

我们经历了其中的多个:

[all(x in i for x in (2,3)) for i in mylist] 
# [True, True, True, False]  
# sum([True, True, True, False]) = 3 
# And we assign them back to the tuple