2

我有一个看起来像的 python 列表/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

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

以上如何在 Excel 和 Python 中实现?

4

2 回答 2

3

您可能应该使用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 解决方案。

于 2013-03-04T12:52:53.710 回答
3

在 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 确认并复制下来 - 这将为您提供所有零序列长度的列表 - 当数字用完时,您会得到空白

If data is in a row rather than a column you need to revise that slightly.....

于 2013-03-04T13:13:51.337 回答