程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

python Make a list of intervals with sequential numbers

編輯:Python
def interval_extract(list):
list = sorted(set(list))
range_start = previous_number = list[0]
for number in list[1:]:
if number == previous_number + 1:
previous_number = number
else:
yield [range_start, previous_number]
range_start = previous_number = number
yield [range_start, previous_number]
if __name__ == "__main__":
# Driver code
l = [2, 3, 4, 5, 7, 8, 9, 11, 15, 16]
print(list(interval_extract(l)))
The yield statement suspends function’s execution
and sends a value back to the caller,
but retains enough state to enable function to resume
where it is left off.
When resumed, the function continues execution immediately
after the last yield run.
This allows its code to produce a series of values over time,
rather than computing them at once and sending them back like a list.

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved