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

1
  • Where are you stuck exactly? iterating by 2? working with strings? Commented Oct 30, 2017 at 7:34

3 Answers 3

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']
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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']

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.