使用python或excel查找每组连续值的长度

我有一个python list / excel范围,看起来像

[0,0,0,0,1,1,0,0,1,1,1,1,1,0,1,0,0,0,0,0,0,0,1,1,0,0,0] . 

我想要以下输出:

 length of 1st set of zeros - 4 length of 2nd set of zeros - 2 length of 3rd set of zeros - 1 length of 4th set of zeros - 7 length of 5th set of zeros - 3 

我已经在Excel中尝试了" COUNTIF($D2:D$2,D2)"这个公式" COUNTIF($D2:D$2,D2)"它帮助我find第n个值,但是我不确定如何find每个连续值的长度。

如何在Excel和Python中实现上述function?

你应该使用itertools.groupby

 counter = 1 suffixes = {1: 'st', 2:'nd', 3:'rd'} for key, group in itertools.groupby(the_sequence): if key == 0: print 'The length of {}{} sequence of zeros is: {}'.format(counter, suffixes.get(counter, 'th'), len(tuple(group))) counter += 1 

输出:

 The length of 1st sequence of zeros is: 4 The length of 2nd sequence of zeros is: 2 The length of 3rd sequence of zeros is: 1 The length of 4th sequence of zeros is: 7 The length of 5th sequence of zeros is: 3 

不幸的是,我不是一个excel用户,我不能帮助你的Excel解决scheme。

在Excel中,假设在D2:D20有数据,则可以在F2中使用此“数组公式”

=IFERROR(INDEX(FREQUENCY(IF($D$2:$D$20=0,ROW($D$2:$D$20)),IF(OFFSET($D$2:$D$20,1,0)<>0,IF($D$2:$D$20=0,ROW($D$2:$D$20)))),ROWS(F$2:F2)),"")

用CTRL + SHIFT + ENTER确认并复制下来 – 这将给你一个所有零序列长度的列表 – 当数字用完时,你会得到空白

如果数据是连续的,而不是列,则需要稍微修改一下…..