Python | Selective Merge in String list
Last Updated :
09 Apr, 2023
Sometimes, while working with Python lists, we can have a problem in which we need to perform the merge operation. There can be various modifications to merge. One such can be replacing every character except a particular character. Let's see different ways in which this task can be performed.
Method #1 : Using list comprehension + join() + zip() The combination of above methods can be used to perform this task. In this, we combine the like elements using zip() and merge operation is performed using join(). List comprehension is used to provide logic and iterations.
Python3
# Python3 code to demonstrate working of
# Selective Merge in String list
# using list comprehension + join() + zip()
# initialize lists
test_list1 = ["abc", "de", "efgh"]
test_list2 = ["gfg", "is", "good"]
# printing original lists
print("The original list 1 : " + str(test_list1))
print("The original list 2 : " + str(test_list2))
# initialize exempt char
exm_chr = 'g'
# Selective Merge in String list
# using list comprehension + join() + zip()
res = [''.join(l if l == exm_chr else k for k, l in zip(i, j))
for i, j in zip(test_list1, test_list2)]
# printing result
print("The resultant list after Selective Merge : " + str(res))
Output : The original list 1 : ['abc', 'de', 'efgh']
The original list 2 : ['gfg', 'is', 'good']
The resultant list after Selective Merge : ['gbg', 'de', 'gfgh']
Time complexity: O(M^N) as the number of combinations generated is M choose N.
Auxiliary space: O(M^N) as the size of the resultant list is also M choose N.
Method #2: Using map() + lambda() + join() + zip() The combination of above functions can also be used to perform this task. In this, we use map() and join() to perform task performed by list comprehension. Rest all task is performed similar to above method.
Python3
# Python3 code to demonstrate working of
# Selective Merge in String list
# using map() + lambda() + join() + zip()
# initialize lists
test_list1 = ["abc", "de", "efgh"]
test_list2 = ["gfg", "is", "good"]
# printing original lists
print("The original list 1 : " + str(test_list1))
print("The original list 2 : " + str(test_list2))
# initialize exempt char
exm_chr = 'g'
# Selective Merge in String list
# using map() + lambda() + join() + zip()
def temp(ele): return ''.join([i if j != exm_chr else j for i, j in ele])
res = list(map(temp, (map(lambda k: zip(*k), zip(test_list1, test_list2)))))
# printing result
print("The resultant list after Selective Merge : " + str(res))
Output : The original list 1 : ['abc', 'de', 'efgh']
The original list 2 : ['gfg', 'is', 'good']
The resultant list after Selective Merge : ['gbg', 'de', 'gfgh']
Time complexity: O(M^N) as the number of combinations generated is M choose N.
Auxiliary space: O(M^N) as the size of the resultant list is also M choose N.
Method #3: Using for loop and zip()
- Initialize two lists test_list1 and test_list2 containing string elements.
- Initialize a variable exm_chr with a character that will be exempted from merging.
- Initialize an empty list res to store the resultant strings.
- Use zip() function to combine the elements of test_list1 and test_list2 based on the index.
- Use a loop to iterate through each element in the combined list:
a. Initialize an empty string temp to store the merged string for the current elements.
b. Use another loop to iterate through each character of the current element.
c. If the character in test_list2 for the current position is not equal to exm_chr, append the corresponding character from test_list1 to temp. Otherwise, append the exm_chr.
d. Append the temp to the res list. - Print the resultant list res.
Python3
test_list1 = ["abc", "de", "efgh"]
test_list2 = ["gfg", "is", "good"]
exm_chr = "g"
res = []
for s1, s2 in zip(test_list1, test_list2):
temp = ""
for c1, c2 in zip(s1, s2):
if c2 != exm_chr:
temp += c1
else:
temp += c2
res.append(temp)
print("The resultant list after Selective Merge : ", res)
#This code is contributed by vinay pinjala.
OutputThe resultant list after Selective Merge : ['gbg', 'de', 'gfgh']
Time complexity: O(N*M)
The two outer loops iterate through the input lists, so their time complexity is O(n), where n is the length of the lists.
The two inner loops iterate through the characters in each string, so their time complexity is O(m), where m is the maximum length of a string in the lists.
The overall time complexity of the algorithm is O(n * m), because the outer and inner loops are nested.
Auxiliary Space: O(N*M)
The space used by the input lists is O(n * m) because they contain n strings of maximum length m.
The space used by the output list is also O(n * m) because it contains n strings of maximum length m.
The space used by the temporary string variable temp is O(m) because it can hold one string of maximum length m at a time.
The overall space complexity of the algorithm is O(n * m) because the input and output lists and the temporary string variable all have this space complexity.
Similar Reads
Python | Ways to merge strings into list Given n strings, the task is to merge all strings into a single list. While developing an application, there come many scenarios when we need to operate on the string and convert it as some mutable data structure, say list. There are multiple ways we can convert strings into list based on the requir
4 min read
Python - Substring presence in Strings List Given list of substrings and list of string, check for each substring, if they are present in any of strings in List. Input : test_list1 = ["Gfg", "is", "best"], test_list2 = ["I love Gfg", "Its Best for Geeks", "Gfg means CS"] Output : [True, False, False] Explanation : Only Gfg is present as subst
5 min read
Python | Split flatten String List Sometimes, while working with Python Strings, we can have problem in which we need to perform the split of strings on a particular deliminator. In this, we might need to flatten this to a single String List. Let's discuss certain ways in which this task can be performed. Method #1 : Using list compr
7 min read
Python | Merge Tuple String List values to String Sometimes, while working with records, we can have a problem in which any element of record can be of type string but mistakenly processed as list of characters. This can be a problem while working with a lot of data. Let's discuss certain ways in which this problem can be solved. Method #1: Using l
7 min read
Python | Selective Merge list every Nth position Sometimes, while working with Python list, we can come into a problem in which we need to perform merging in list. A simple merge of list is easier to perform. But sometimes, we need to handle variations in merge. One such can be merge one list with other at every Nth element. This particular proble
5 min read
Python | Delimited String List to String Matrix Sometimes, while working with Python strings, we can have problem in which we need to convert String list which have strings that are joined by deliminator to String Matrix by separation by deliminator. Lets discuss certain ways in which this task can be performed. Method #1 : Using loop + split() T
5 min read
Python | Merge Range Characters in List Sometimes, we require to merge some of the elements as single element in the list. This is usually with the cases with character to string conversion. This type of task is usually required in development domain to merge the names into one element. Letâs discuss certain ways in which this can be perf
6 min read
Subtract String Lists in Python The task of subtracting string lists in Python involves removing elements of one list from another while preserving the order of the remaining elements. Given two lists, the goal is to filter out strings from the first list that are present in the second list. For example, with a = ["apple", "banana
3 min read
Tokenizing Strings in List of Strings - Python The task of tokenizing strings in a list of strings in Python involves splitting each string into smaller units, known as tokens, based on specific delimiters. For example, given the list a = ['Geeks for Geeks', 'is', 'best computer science portal'], the goal is to break each string into individual
2 min read
String Repetition and spacing in List - Python We are given a list of strings and our task is to modify it by repeating or adding spaces between elements based on specific conditions. For example, given the list `a = ['hello', 'world', 'python']`, if we repeat each string twice, the output will be `['hellohello', 'worldworld', 'pythonpython']. U
2 min read