简体   繁体   中英

How to merge two lists horizontally

EDIT: I am using zip, but as my environment is in Python 2.x the zip code is matching character by character instead of items in list 1 with items in list 2

I am trying to merge two lists horizontally. My sample dataset is something like this:

test_list1 = ['1', '4', '5', '6', '5'] 
test_list2 = ['a','b','c','d','e']

I want the outcome of the combined list to look like this:

Combined_list = ['1a', '4b', '5c', '6d', '5e']

您可以使用 zip:

[f"{x[0]}{x[1]}" for x in zip(test_list1, test_list2)]

You can use zip to iterate through two lists in parallel

test_list1 = ['1', '4', '5', '6', '5'] 
test_list2 = ['a','b','c','d','e']

Combined_list = [f_item + s_item for f_item, s_item in zip(test_list1, test_list2)]

By using zip and join :

test_list1 = ['1', '4', '5', '6', '5'] 
test_list2 = ['a','b','c','d','e']

[''.join(t) for t in zip(test_list1, test_list2)]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM