第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

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

標識列表中的連續(xù)數(shù)字組

標識列表中的連續(xù)數(shù)字組

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

3 回答

?
猛跑小豬

TA貢獻1858條經(jīng)驗 獲得超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]]

電碼

應(yīng)用此工具,我們創(chuàng)建了一個生成器函數(shù),用于查找連續(xù)數(shù)字的范圍。

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]

這個來源實現(xiàn)模擬經(jīng)典配方(如@Nadia Alramli所示)。

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


查看完整回答
反對 回復(fù) 2019-06-29
?
UYOU

TA貢獻1878條經(jīng)驗 獲得超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)]


查看完整回答
反對 回復(fù) 2019-06-29
  • 3 回答
  • 0 關(guān)注
  • 455 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號