计算lis中连续的零

2024-04-20 03:53:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我必须编写一个程序,给出一个列表中所有零的突发长度(只包括一个零)。例如

[1, 0, 0, 0, 0, 3, 7, 0, 0, 0, 0, 0, 0, 50, 0]

会给出:

^{2}$

以下是我目前所写的:

listsize = int(input("Please enter the length of the list: "))
burstList = []

for i in range(0, listsize):
    N = int(input("Please enter a number: "))
    burstList.append(N)

print("Your final list is: ", burstList)

counter = 0
output = []
burst_open = False
for i in range(len(burstList)):
    if i == 0:
        counter += 1
        burst_open = True
    else:
        if burst_open:
        output.append(counter)
        counter = 0
        burst_open = False
print(output)

我认为这段代码应该可以工作,但是当我在示例列表中运行它时,它只给了我[1]作为输出。任何帮助都将不胜感激!在


Tags: thein列表forinputoutputcounteropen
3条回答

使用itertools.groupby

In [889]: lst = [1, 0, 0, 0, 0, 3, 7, 0, 0, 0, 0, 0, 0, 50, 0]                                                                                                                                              

In [890]: [len(list(g)) for k, g in itertools.groupby(lst) if k == 0]                                                                                                                                       
Out[890]: [4, 6, 1]

这里我们迭代组,得到grouper key为0时每个组的长度。在

在上面,我们用迭代器创建一个列表来获取长度。我们可以在不创建中间列表的情况下获得迭代器的计数,方法是:

^{pr2}$

sum(1 for _ in g)只使用迭代器并对元素计数,而不创建一个新的列表来计算其元素。在

就速度而言,两种长度求解都具有O(N)的时间复杂度。但是在实践中,list一个会更快,因为C级循环。在

你的for应该在burstList上。在

另外,在循环完成后,如果counter不是0,则必须追加counter(如果数组以0结尾),那么在最后一次突发时永远不会达到else条件。在

burstList = [1, 0, 0, 0, 0, 3, 7, 0, 0, 0, 0, 0, 0, 50, 0]

counter = 0
output = []
burst_open = False
for i in burstList:
    if i == 0:
        counter += 1
        burst_open = True
    else:
        if burst_open:
            output.append(counter)
        counter = 0
        burst_open = False

if counter !=0:
    output.append(counter)
print(output)

输出:

[4, 6, 1]

我会这样做:

ll = [1, 0, 0, 0, 0, 3, 7, 0, 0, 0, 0, 0, 0, 50, 0]


def value_bursts(items, value=0):
    result = []
    counter = 0
    for item in items:
        if item == value:
            counter += 1
        elif counter > 0:
            result.append(counter)
            counter = 0
    if counter > 0:
        result.append(counter)
    return result


value_bursts(ll)
# [4, 6, 1]

我已经将它包装成一个函数,并去掉了无用的burst_open标志。在

请注意,虽然来自@heemayl的1线当然很优雅,但它可能不是最快的:

^{pr2}$
%timeit value_bursts(ll * 1000)
# 1000 loops, best of 3: 643 µs per loop
%timeit value_bursts_2(ll * 1000)
# 1000 loops, best of 3: 1.11 ms per loop

相关问题 更多 >