亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

標識列表中的連續數字組

標識列表中的連續數字組

慕森王 2019-06-29 09:58:08
標識列表中的連續數字組我想在一個列表中識別一組連續的數字,以便:myfunc([2, 3, 4, 5, 12, 13, 14, 15, 16, 17, 20])返回:[(2,5), (12,17), 20]我想知道做這件事的最好方法是什么(尤其是在Python中內置了一些東西的時候)。編輯:我最初忘記提到,單個數字應該作為單個數字返回,而不是范圍。
查看完整描述

3 回答

?
猛跑小豬

TA貢獻1858條經驗 獲得超8個贊

more_itertools.consecutive_groups是在4.0版中添加的。

演示

import more_itertools as mit


iterable = [2, 3, 4, 5, 12, 13, 14, 15, 16, 17, 20][list(group) for group in mit.consecutive_groups(iterable)]# [[2, 3, 4, 5], [12, 13, 14, 15, 16, 17], [20]]

電碼

應用此工具,我們創建了一個生成器函數,用于查找連續數字的范圍。

def find_ranges(iterable):
    """Yield range of consecutive numbers."""
    for group in mit.consecutive_groups(iterable):
        group = list(group)
        if len(group) == 1:
            yield group[0]
        else:
            yield group[0], group[-1]iterable = [2, 3, 4, 5, 12, 13, 14, 15, 16, 17, 20]list(find_ranges(iterable))# [(2, 5), (12, 17), 20]

這個來源實現模擬經典配方(如@Nadia Alramli所示)。

注:more_itertools第三方包是否可通過pip install more_itertools.


查看完整回答
反對 回復 2019-06-29
?
UYOU

TA貢獻1878條經驗 獲得超4個贊

“天真”的解決方案,我覺得至少有點可讀性。

x = [2, 3, 4, 5, 12, 13, 14, 15, 16, 17, 22, 25, 26, 28, 51, 52, 57]def group(L):
    first = last = L[0]
    for n in L[1:]:
        if n - 1 == last: # Part of the group, bump the end
            last = n        else: # Not part of the group, yield current group and start a new
            yield first, last
            first = last = n    yield first, last # Yield the last group>>>print list(group(x))[(2, 5), (12, 17), (22, 22), (25, 26), (28, 28), (51, 52), (57, 57)]


查看完整回答
反對 回復 2019-06-29
  • 3 回答
  • 0 關注
  • 460 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號