计算列表中的连续数字

Pat*_*eli 5 python loops list user-defined-functions

我找不到与我的问题足够相似的问题,无法找到令人满意的答案。

我对 Python (3.4.3) 还很陌生。我试图通过将输入列表的每个元素与其中的下一个元素进行比较,使用 for 循环将元素添加到输出列表。

到目前为止,这是我的代码:

random_list=[1,4,5,6,7,9,19,21,22,23,24]

def count_consec(random_list):
    count=1
    consec_list=[]
    for i in listrand:
        if listrand[i] == listrand[i+1]+1:
            count+=1
        else:
            list.append(count)
    return consec_list
Run Code Online (Sandbox Code Playgroud)

基本上,我想添加consec_list[]表示random_list[].

我希望在这种情况下我的输出如下所示:

[1,4,1,1,4]
Run Code Online (Sandbox Code Playgroud)

例如,有 1 个单数,后面跟着 4 个连续数字,后面跟着 1 个单数,后面跟着 1 个单数,后面跟着 4 个连续数字。

我尝试了很多不同的方法,我已经得到了构建列表的功能,但所有元素都是 1。

Tri*_*tan 6

您可以采取这样的方法:

def countlist(random_list):
    retlist = []
    # Avoid IndexError for  random_list[i+1]
    for i in range(len(random_list) - 1):
        # Check if the next number is consecutive
        if random_list[i] + 1 == random_list[i+1]:
            count += 1
        else:
            # If it is not append the count and restart counting
            retlist.append(count)
            count = 1
    # Since we stopped the loop one early append the last count
    retlist.append(count)
    return retlist
Run Code Online (Sandbox Code Playgroud)