Reputation: 349
I am having a hard time to find a solution to merge two different type of element within the list.
list_i = ['teacher', '10', 'student', '100', 'principle', '2']
Result:
list_1 = ['teacher:10', 'student:100', 'principle:2']
Any help is greatly appreciated!!
Upvotes: 2
Views: 7446
Reputation: 44465
Using more_itertools
, a third-party library, you can apply a sliding window technique:
> pip install more_itertools
Code
import more_itertools as mit
iterable = ['teacher', '10', 'student', '100', 'principle', '2']
[":".join(i) for i in mit.windowed(iterable, 2, step=2)]
# ['teacher:10', 'student:100', 'principle:2']
Alternatively apply the grouper
itertools recipe, which is also implemented in more_itertools
.
[":".join(i) for i in mit.grouper(2, iterable)]
# ['teacher:10', 'student:100', 'principle:2']
Upvotes: 0
Reputation: 1438
Use following code
[':'.join(item) for item in zip(list_i[::2],list_i[1::2])]
This will just slice the list in 2 parts and joins them with zip
Upvotes: 5
Reputation: 24052
This will work:
[list_i[i] + ":" + list_i[i+1] for i in range(0, len(list_i), 2)]
This produces:
['teacher:10', 'student:100', 'principle:2']
Upvotes: 6