View Discussion
Improve Article
Save Article
View Discussion
Improve Article
Save Article
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 the development domain to merge the names into one element. Let’s discuss certain ways in which this can be performed.
Method #1 : Using join[] + List Slicing
The join function can be coupled with list slicing which can perform the task of joining each character in a range picked by the list slicing functionality.
test_list
=
[
'I'
,
'L'
,
'O'
,
'V'
,
'E'
,
'G'
,
'F'
,
'G'
]
print
[
"The original list is : "
+
str
[test_list]]
test_list[
5
:
8
]
=
[''.join[test_list[
5
:
8
]]]
print
[
"The list after merging elements : "
+
str
[test_list]]
Output:
The original list is : ['I', 'L', 'O', 'V', 'E', 'G', 'F', 'G'] The list after merging elements : ['I', 'L', 'O', 'V', 'E', 'GFG']
Method #2 : Using
reduce[] + lambda + list slicing
The task of joining each element in a range is performed by reduce function and lambda. reduce function performs the task for each element in the range which is defined by the lambda function. It works with Python2 only
test_list
=
[
'I'
,
'L'
,
'O'
,
'V'
,
'E'
,
'G'
,
'F'
,
'G'
]
print
[
"The original list is : "
+
str
[test_list]]
test_list[
5
:
8
]
=
[
reduce
[
lambda
i, j: i
+
j, test_list[
5
:
8
]]]
print
[
"The list after merging elements : "
+
str
[test_list]]
Output:
The original list is : ['I', 'L', 'O', 'V', 'E', 'G', 'F', 'G'] The list after merging elements : ['I', 'L', 'O', 'V', 'E', 'GFG']
I have a list of string like:
s = [["abc","bcd","cde"],["123","3r4","32f"]]
Now I want to convert this to the following:
output = ["abcbcdcde","1233r432f"]
What is the pythonic way to do this? THanks
asked Mar 29, 2012 at 4:24
0
>>> [''.join[x] for x in s]
['abcbcdcde', '1233r432f']
answered Mar 29, 2012 at 4:25
1
>>> map[''.join, s]
['abcbcdcde', '1233r432f']
That should do it
answered Mar 29, 2012 at 4:29
jamylakjamylak
123k29 gold badges227 silver badges227 bronze badges
2
output = []
for grp in s:
output.append[''.join[grp]]
answered Mar 29, 2012 at 4:27
Jonathon ReinhartJonathon Reinhart
127k32 gold badges245 silver badges316 bronze badges
How about this:
>>> map[lambda x: ''.join[x], s]
['abcbcdcde', '1233r432f']
answered Mar 29, 2012 at 4:29
Wil CooleyWil Cooley
8906 silver badges18 bronze badges
1
Not a real answer, just want to check, what about reduce and operator.add, i read that in such a way both of them would perform quite fast and effective, or i am wrong?
s = [["abc","bcd","cde"],["123","3r4","32f"]]
from operator import add
[reduce[add, x] for x in s]
answered Mar 29, 2012 at 4:36
Artsiom RudzenkaArtsiom Rudzenka
26.9k4 gold badges32 silver badges51 bronze badges
1