Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to merge elements in list in python with condition?

Tags:

python

list

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

like image 579
dlfjj Avatar asked Dec 03 '25 18:12

dlfjj


1 Answers

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']
like image 198
Tom Karzes Avatar answered Dec 06 '25 08:12

Tom Karzes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!