计数列表中的子列表 [英] Counting sublists in a list
本文介绍了计数列表中的子列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
L=[2,4,5,6,2,1,6,6,3,2,4,5,3,4,5]
我想知道任意子序列出现了多少次,例如s=[2,4,5]
将返回2次.
I want to know how many times an arbitrary sub-sequence shows up, s=[2,4,5]
for instance would return 2 times.
我尝试了L.count(s)
,但是它不起作用,因为我认为它希望查找的是类似[random numbers ... [2,4,5] ... random numbers]
的东西,而不是没有括号的2,4,5
.
I tried L.count(s)
but it does not work because I think it is expecting to look for something like [random numbers ... [2,4,5] ... random numbers]
instead of 2,4,5
without the brackets.
推荐答案
>>> L = [2,4,5,6,2,1,6,6,3,2,4,5,3,4,5]
>>> s = [2,4,5]
>>> sum(1 for i in range(len(L)) if L[i:i+len(s)]==s)
2
几乎相同,但略短(使用True
的行为类似于数字1
的事实):
Almost the same thing, slightly shorter (uses the fact that True
can behave like the number 1
):
>>> sum(L[i:i+len(s)]==s for i in range(len(L)))
2
这篇关于计数列表中的子列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文