2

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!!

dlfjj
  • 349
  • 1
  • 8
  • 26

3 Answers3

6

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']
Tom Karzes
  • 22,815
  • 2
  • 22
  • 41
5

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

daemon24
  • 1,388
  • 1
  • 11
  • 23
0

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']
pylang
  • 40,867
  • 14
  • 129
  • 121