Sunday, December 29, 2024
Google search engine
HomeLanguagesPython – Segregate elements by delimiter

Python – Segregate elements by delimiter

Given a list of Strings, segregate each string by delimiter and output different lists for prefixes and suffixes.

Input: test_list = [“7$2”, “8$5”, “9$1”], delim = “$” 
Output : [‘7’, ‘8’, ‘9’], [‘2’, ‘5’, ‘1’] 
Explanation  Different lists for prefixes and suffixes of “$” 

Input  test_list = [“7*2”, “8*5”, “9*1”], delim = “*” 
Output : [‘7’, ‘8’, ‘9’], [‘2’, ‘5’, ‘1’] 
Explanation: Different lists for prefixes and suffixes of “*”

Method #1 : Using list comprehension + split()

This is one of the ways in which this task can be performed. In this, we perform segregation using split(), the first part of the split is compiled to one list comprehension and next to the other.

Python3




# Python3 code to demonstrate working of
# Segregate elements by delimiter
# Using list comprehension + split()
 
# initializing list
test_list = ["7$2", "8$5", "9$1", "8$10", "32$6"]
 
# printing original list
print("The original list : " + str(test_list))
 
# using delim
delim = "$"
 
# using split() to split and different list comprehension
# assigns results to different lists
res1, res2 = [ele.split(delim)[0] for ele in test_list], [
    ele.split(delim)[1] for ele in test_list]
 
# printing result
print("The filtered list 1 : " + str(res1))
print("The filtered list 2 : " + str(res2))


Output

The original list : ['7$2', '8$5', '9$1', '8$10', '32$6']
The filtered list 1 : ['7', '8', '9', '8', '32']
The filtered list 2 : ['2', '5', '1', '10', '6']

Time Complexity: O(n), where n is the number of elements in the list “test_list”.
Auxiliary Space: O(n), where n is the number of elements in the list “test_list”.

Method #2 : Using map() + list + zip() + generator expression

The combination of above functions can be used to solve this problem. In this, we extend the list construction logic using map() and zip() is used to perform split() functionality to each element.

Python3




# Python3 code to demonstrate working of
# Segregate elements by delimiter
# Using map() + list + zip() + generator expression
 
# initializing list
test_list = ["7$2", "8$5", "9$1", "8$10", "32$6"]
 
# printing original list
print("The original list : " + str(test_list))
 
# using delim
delim = "$"
 
# map() used to cast different sections to different lists
res1, res2 = map(list, zip(*(ele.split(delim) for ele in test_list)))
 
# printing result
print("The filtered list 1 : " + str(res1))
print("The filtered list 2 : " + str(res2))


Output

The original list : ['7$2', '8$5', '9$1', '8$10', '32$6']
The filtered list 1 : ['7', '8', '9', '8', '32']
The filtered list 2 : ['2', '5', '1', '10', '6']

Time Complexity: O(n2)
Auxiliary Space: O(n)

Method #3 : Using index() method and slicing

Python3




# Python3 code to demonstrate working of
# Segregate elements by delimiter
 
# initializing list
test_list = ["7$2", "8$5", "9$1", "8$10", "32$6"]
 
# printing original list
print("The original list : " + str(test_list))
 
# using delim
delim = "$"
res1 = []
res2 = []
for i in test_list:
    a = i[:i.index(delim)]
    b = i[i.index(delim)+1:]
    res1.append(a)
    res2.append(b)
 
# printing result
print("The filtered list 1 : " + str(res1))
print("The filtered list 2 : " + str(res2))


Output

The original list : ['7$2', '8$5', '9$1', '8$10', '32$6']
The filtered list 1 : ['7', '8', '9', '8', '32']
The filtered list 2 : ['2', '5', '1', '10', '6']

Time Complexity: O(n), where n is the length of the test_list. 
Auxiliary Space: O(n), where n is the length of the test_list

Method #4: Using slicing

Python3




# Python3 code to demonstrate working of
# Segregate elements by delimiter
 
# initializing list
test_list = ["7$2", "8$5", "9$1", "8$10", "32$6"]
 
# printing original list
print("The original list : " + str(test_list))
 
# using delim
delim = "$"
 
res = []
for i in test_list:
    value = i.split(delim)
    res.append(value[0])
    res.append(value[1])
 
# printing result
print("The filtered list 1 : " + str(res[::2]))
print("The filtered list 2 : " + str(res[1::2]))


Output

The original list : ['7$2', '8$5', '9$1', '8$10', '32$6']
The filtered list 1 : ['7', '8', '9', '8', '32']
The filtered list 2 : ['2', '5', '1', '10', '6']

Time complexity: O(n), where n is the number of elements in the test_list.
Auxiliary space: O(n), where n is the number of elements in the test_list.

Method #5: Using a dictionary and a loop

This code first creates an empty dictionary res_dict. It then loops through each element of the list, splits it by the delimiter, and stores the key and value in the dictionary. If the key is not already in the dictionary, it creates a new empty list for that key. Then it appends the key to the res1 list, and extends the res2 list with the values for that key.

Python




test_list = ["7$2", "8$5", "9$1", "8$10", "32$6"]
delim = "$"
 
res_dict = {}
for i in test_list:
    key, value = i.split(delim)
    if key not in res_dict:
        res_dict[key] = []
    res_dict[key].append(value)
 
res1 = []
res2 = []
for key, values in res_dict.items():
    res1.append(key)
    res2.extend(values)
 
print("The filtered list 1 : " + str(res1))
print("The filtered list 2 : " + str(res2))


Output

The filtered list 1 : ['9', '8', '7', '32']
The filtered list 2 : ['1', '5', '10', '2', '6']

Time complexity: O(n), where n is the length of the input list.
Auxiliary space: O(n), where n is the length of the input list.

Method #6: Using a defaultdict

Step-by-step approach:

  • Import defaultdict from the collections module
  • Define the test_list and the delimiter as before
  • Initialize a defaultdict with the list constructor. This will create a dictionary with default values as empty lists.
  • Loop through the test_list, splitting each element using the delimiter, and appending the value to the dictionary corresponding to the key.
  • Convert the keys of the dictionary to a list for the first filtered list (res1).
  • For the second filtered list (res2), use a nested list comprehension to extract all the values from the dictionary and flatten them into a single list.
  • Print the results 

Python3




from collections import defaultdict
 
test_list = ["7$2", "8$5", "9$1", "8$10", "32$6"]
delim = "$"
 
res_dict = defaultdict(list)
 
for i in test_list:
    key, value = i.split(delim)
    res_dict[key].append(value)
 
res1 = list(res_dict.keys())
res2 = [value for values in res_dict.values() for value in values]
 
print("The filtered list 1 : " + str(res1))
print("The filtered list 2 : " + str(res2))


Output

The filtered list 1 : ['7', '8', '9', '32']
The filtered list 2 : ['2', '5', '10', '1', '6']

Time complexity: O(n)
Auxiliary space: O(n) (for the dictionary)

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments