daiyue daiyue - 2 months ago 7
Python Question

How to put sequential numbers into lists from a list

I have a list numbers say,

[1,2,3,4,6,8,9,10,11]


First, I want to get the sum of the differences (step size) between the numbers
(n, n+1)
in the list.

Second, if a set of consecutive numbers having a difference of 1 between them, put them in a list, i.e. there are two such lists in this example,

[1,2,3]


[8,9,10,11]


and then put the rest numbers in another list, i.e. there is only one such list in the example,

[6]
.

Third, get the lists with the max/min sizes from the sequential lists, i.e.
[1,2,3]
,
[8,9,10,11]
in this example, the max list is,

[8,9,10,11]


min list is

[1,2,3]
.

What's the best way to implement this?

Answer

First, I want to get the sum of the differences (step size) between the numbers (n, n+1) in the list.

Use sum on the successive differences of elements in the list:

>>> sum(lst[i] - x for i, x in enumerate(lst[:-1], start=1))
10

Second, if a set of consecutive numbers having a difference of 1 between them, put them in a list, i.e. there are two such lists in this example, and then put the rest numbers in another list, i.e. there is only one such list in the example,

itertools.groupby does this by grouping on the difference of each element on a reference itertools.count object:

>>> from itertools import groupby, count
>>> c = count()    
>>> result = [list(g) for i, g in groupby(lst, key=lambda x: x-next(c))]
>>> result
[[1, 2, 3, 4], [6], [8, 9, 10, 11]]

Third, get the lists with the max/min sizes from above

max and min with the key function as sum:

>>> max(result, key=sum)
[8, 9, 10, 11]
>>> min(result, key=sum)
[6] #??? shouldn't this be [6]
Comments