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.