[SOLVED] I want to get only those subset which have k elements in it

Issue

This Content is from Stack Overflow. Question asked by ABHAY PRATAP

L=[1,2,3,4,5,6,7]
K=2
The ans i want
L=[[1,2],[2,3],[3,4][4,5],[5,6],[6,7]]
In ans there should be no subset which doesn’t have k elements in it



Solution

You can iterate a number starting from 0 to the maximum number from which at least K elements exists, then create the list of list out the items starting and ending with required indices, you can use List Comprehension to accomplish this:

>>> [L[i:i+K] for i in range(len(L)-K+1)]

[[1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 7]]


This Question was asked in StackOverflow by ABHAY PRATAP and Answered by ThePyGuy It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?