簡體   English   中英

計算列表中的連續數字

[英]Counting consecutive numbers in a list

我找不到一個與我的問題足夠相似的問題,我可以找到一個令人滿意的答案。

我對 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

基本上,我要添加到consec_list[]值表示如何號碼的連續塊的長度random_list[]

我希望在這種情況下我的輸出如下所示:

[1,4,1,1,4]

例如,有一個單數,后跟 4 個連續的數字,然后是 1 個單數,然后是 1 個單數,然后是 4 個連續的數字。

我嘗試了很多不同的方法,並獲得了構建列表的功能,但所有元素都是 1。

你可以采取這樣的方法:

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

以下代碼修復了它。 您正在迭代列表本身的元素而不是您引用的計數器。

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

def count_consec(listrand):
    count=1
    consec_list=[]
    for i in range(len(listrand[:-1])):
        if listrand[i]+1 == listrand[i+1]:
            count+=1
        else:
            consec_list.append(count)
            count=1

    # Account for the last iteration
    consec_list.append(count)     

    return consec_list

print(count_consec(random_list))      

返回這個:

[1, 4, 1, 1, 4]

您的代碼存在一些問題,其中包括未定義的變量,或者使用列表中的元素i作為該元素的索引,但您還會收到最后一個元素的索引錯誤,並且您永遠不會將最后一個計數添加到結果列表。

相反,我建議使用zip(lst, lst[1:])配方來迭代列表中的元素對,並使用consec[-1]訪問和修改列表中已有的計數。

def count_consec(lst):
    consec = [1]
    for x, y in zip(lst, lst[1:]):
        if x == y - 1:
            consec[-1] += 1
        else:
            consec.append(1)
    return consec

random_list=[1,4,5,6,7,9,19,21,22,23,24]
print(count_consec(random_list))
# [1, 4, 1, 1, 4]

或者,您可以從每個元素中減去索引。 這樣,連續的連續元素最終將成為相同的元素。 現在,您可以使用itertools.groupby對這些元素進行分組和計數。

>>> random_list=[1,4,5,6,7,9,19,21,22,23,24]
>>> [e-i for i, e in enumerate(random_list)]
[1, 3, 3, 3, 3, 4, 13, 14, 14, 14, 14]
>>> [sum(1 for _ in g) for _, g in itertools.groupby(_)]
[1, 4, 1, 1, 4]

這是我的版本

假設你有一個數字列表,你想遍歷它並計算連續的條紋:

list_of_nums = [4,5,7,8,2,1,3,5,7,6,8,9,9,9,2,2]

你可以這樣做:

streak_count = []
counter = 1
for i in range(len(list_of_nums)):
    if i != (len(list_of_nums) - 1):
        diff = list_of_nums[i+1] - list_of_nums[i]
        if diff == 1:
            counter += 1
        else:
            streak_count.append(counter)
            counter = 1
    else:
        streak_count.append(counter)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM