GDog
GDog

Reputation: 165

List Split into Consecutive Lists of 2 - Ascending by 1

For the list:

list_x=[1,2,3,6,7,8,1,2,6,7]

How do you split this into separate lists of 2 elements, that are consectutive and ascending by 1.

Desired Output

list_a=[1,2]
list_b=[2,3]
list_c=[6,7]
list_d=[7,8]
list_e=[1,2]
list_f=[6,7]

Note that 'list_x' can be any length and it is required to split this list into pairs of 2. Each pair is consecutive by plus 1.

This is an attempt:

list_a = list_x.ne.shift(fill_value=list_a.iat[0])

Thankyou.

Upvotes: 1

Views: 96

Answers (2)

azro
azro

Reputation: 54148

For consecutive pairs with consecutive number it is

values = [[a, b] for a, b in zip(list_x, list_x[1:]) if a + 1 == b]
print(values)  # [[1, 2], [2, 3], [6, 7], [7, 8], [1, 2], [6, 7]]

For all consecutive pairs

values = list(zip(list_x, list_x[1:]))
print(values)  # [(1, 2), (2, 3), (3, 6), (6, 7), (7, 8), (8, 1), (1, 2), (2, 6), (6, 7)]

Upvotes: 3

A.M. Ducu
A.M. Ducu

Reputation: 900

You can also try this:

list_x = [1, 2, 3, 6, 7, 8, 1, 2, 6, 7]

list_new = [[a, b] for a, b in zip(list_x, list_x[1:])]

It should work alright and is pretty simple. You obtain a list of lists that you want.

Upvotes: 1

Related Questions