Emad Ezzeldin
Emad Ezzeldin

Reputation: 23

Sublists Extraction in Python on a specific item in original list

Question

How to extract sublists from a list, each sublist is extracted with an upper and lower edge being a specific item in the list.

Example 1

Input

Sublist_Slicing_edge = 0

mylist = [0,1,0,1,-1,-1,-2,1,2,3,4,0]

Desired Output

list1 = [0,1,0]

list2 = [0,1,-1,-1,-2,1,2,3,4,0]

Example 2

Input

Sublist_Slicing_edge = "I"

mylist = ["I" , "am" , "an" , "Engineer" , "and" , "I" , "am", "also","a" , "Scientist","!","But","I","am","not","a","Mathmatician"]

Desired Output

list1 = ["I" , "am" , "an" , "Engineer" , "and" , "I"]

list2 = ["I" , "am", "also","a" , "Scientist","!","But","I"]

Upvotes: 1

Views: 160

Answers (1)

Rajat Mishra
Rajat Mishra

Reputation: 3770

The solution would require you to do following steps:

  1. find the index position of the specific item in the list

  2. slice the main list based on the index positions found in step 1

  3. Finding the index position of the elem in the list

>>> mylist = ["I" , "am" , "an" , "Engineer" , "and" , "I" , "am", "also","a" , "Scientist","!","But","I","am","not","a","Mathmatician"]
>>> sublist_str = "I"
>>> indexes_list = [i for i,v in enumerate(mylist) if v == sublist_str]
>>> indexes_list
[0, 5, 12]
  1. Creating sublist using the index positions:
>>> [mylist[indexes_list[i]:indexes_list[i+1]+1]  for i in range(len(indexes_list)-1)]
[['I', 'am', 'an', 'Engineer', 'and', 'I'], ['I', 'am', 'also', 'a', 'Scientist', '!', 'But', 'I']]

Upvotes: 1

Related Questions