Python | Save K consecutive items

Python Methods and Functions

Method # 1: Using groupby () + comprehension list
This task can be accomplished using the above functions. In this we will group all the numbers that occur K in sequence. We iterate over the list using comprehension.

# Python3 code to demonstrate how it works
# Save K consecutive elements
# using groupby () + list comprehension

from itertools import groupby

 
# initialize the list

test_list = [ 1 , 1 , 4 , 5 , 5 , 6 , 7 , 7 , 8 ]

 
# prints the original list

print ( "The original list : " + str (test_list))

 
# initialize K

K = 2

  
# Save K consecutive elements
# using groupby () + list comprehension

res = [i for i, j in groupby (test_list) if len ( list (j)) = = K]

 
# print result

print ( "The K consecutive elements are:" + str (res))

Output:

 The original list: [1, 1, 4, 5, 5, 6, 7, 7, 8] The K consecutive elements are: [1, 5, 7] 

C tutorial # 2: Using the comprehension list + slice () + groupby ()
This task can also be accomplished using the above functions. In this we just do the grouping in the same way as above, but the way to retrieve sequential elements is with slice ().

# Python3 code to demonstrate how it works
# Save K consecutive elements
# using groupby () + list comprehension + islice ()

from itertools import groupby, islice

 
# initialize the list

test_list = [ 1 , 1 , 4 , 5 , 5 , 6 , 7 , 7 , 8 ]

 
# print original list

print ( "The original list:" + str (test_list))

 
# initialize K

K = 2

 
# Sokh strip K consecutive elements
# using groupby () + list comprehension + islice ()

res = [i for i, j in groupby (test_list) if len ( list (islice (j, 0 , K))) = = K]

 
# print result

print ( "The K consecutive elements are:" + str (res))

Output:

 The original list: [1, 1, 4, 5, 5, 6, 7, 7, 8] The K consecutive elements are: [1, 5, 7] 




Get Solution for free from DataCamp guru