Home > Software design >  How to get forwaard moving combination of a list in python?
How to get forwaard moving combination of a list in python?

Time:05-07

I have a following list lst = [100,200,300,400]

I need the following output [(100, 200), (200, 300), (300, 400)]

I did some research and used itertools.combinations library for that

[c for c in itertools.combinations(lst, 2)]

if I use the above code I get the following output which produces all combinations. [(100, 200), (100, 300), (100, 400), (200, 300), (200, 400), (300, 400)]

I don't want all the combinations, I only want forward moving combinations how can I get the desired output?

CodePudding user response:

YOu could achieve this using pure python code.

lst = [100,200,300,400]

new_lst = [(lst[a],lst[a 1]) for a in range(len(lst)) if a<len(lst)-1]
print(new_lst)

OUTPUT

[(100, 200), (200, 300), (300, 400)]

AS @hilberts_drinking_problem comment you can use itertools.pairwise also.

from itertools import pairwise
lst = [100,200,300,400]

new_list = list(pairwise(lst))
print(new_list)

OUTPUT:


[(100, 200), (200, 300), (300, 400)]

CodePudding user response:

If you're on a Python 3.10, you can use itertools.pairwise(). Otherwise, you can use zip():

lst = [100,200,300,400]
list(zip(lst, lst[1:]))

This outputs:

[(100, 200), (200, 300), (300, 400)]
  • Related